Golang fmt.Stringer type example

package fmt

Stringer is implemented by any value that has a String method, which defines the “native” format for that value. The String method is used to print values passed as an operand to any format that accepts a string or to an unformatted printer such as Print.

Golang fmt.Stringer type usage example

 func toString(a interface{}) (string, bool) {
 aString, isString := a.(string)
 if isString {
 return aString, true
 }
 aBytes, isBytes := a.([]byte)
 if isBytes {
 return string(aBytes), true
 }
 aStringer, isStringer := a.(fmt.Stringer) // <-- here

 if isStringer {
 return aStringer.String(), true // <-- and here
 }
 return "", false
 }

Reference :

http://golang.org/pkg/fmt/#Stringer

Advertisement