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).
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.
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.
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.
fmt.Stringer
is what you're after.
type Stringer interface {
String() string
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With