Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go interface with String() method

Is there a Go interface in the standard library with:

String() string

?

(Similar to how Java has toString() on java.lang.Object)

Perhaps I just didn't search enough but I didn't see one. Wanted to use one that already exists rather than than making my own (though I guess it really makes no difference with Go's type system).

like image 851
Brad Peabody Avatar asked Oct 10 '13 05:10

Brad Peabody


People also ask

How do you convert interface to string in Golang?

To convert interface to string in Go, use fmt. Sprint function, which gets the default string representation of any value. If you want to format an interface using a non-default format, use fmt. Sprintf with %v verb.

What is interface {} Golang?

interface{} means you can put value of any type, including your own custom type. All types in Go satisfy an empty interface ( interface{} is an empty interface). In your example, Msg field can have value of any type.

How do I instantiate an interface in Go?

Declaring Interface Types Interface describes all the methods of a method set and provides the signatures for each method. To create interface use interface keyword, followed by curly braces containing a list of method names, along with any parameters or return values the methods are expected to have.


1 Answers

fmt.Stringer is what you're after.

type Stringer interface {
        String() string
}
like image 139
Intermernet Avatar answered Oct 27 '22 10:10

Intermernet