patterngoCritical
ToString() function in Go
Viewed 0 times
functiontostringstackoverflow
Problem
The
But it would be nice to be able to pass arbitrary objects which implement a
Is there something like this in Go or do I have to decorate existing types like
strings.Join function takes slices of strings only:s := []string{"foo", "bar", "baz"}
fmt.Println(strings.Join(s, ", "))But it would be nice to be able to pass arbitrary objects which implement a
ToString() function.type ToStringConverter interface {
ToString() string
}Is there something like this in Go or do I have to decorate existing types like
int with ToString methods and write a wrapper around strings.Join?func Join(a []ToStringConverter, sep string) stringSolution
Attach a
Playground: http://play.golang.org/p/Azql7_pDAA
Output
String() string method to any named type and enjoy any custom "ToString" functionality:package main
import "fmt"
type bin int
func (b bin) String() string {
return fmt.Sprintf("%b", b)
}
func main() {
fmt.Println(bin(42))
}Playground: http://play.golang.org/p/Azql7_pDAA
Output
101010Code Snippets
package main
import "fmt"
type bin int
func (b bin) String() string {
return fmt.Sprintf("%b", b)
}
func main() {
fmt.Println(bin(42))
}Context
Stack Overflow Q#13247644, score: 277
Revisions (0)
No revisions yet.