The 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) string
Attach a
String() string
method to any named type and enjoy any custom "ToString" functionality:Playground: http://play.golang.org/p/Azql7_pDAA
Output
I prefer something like the following:
When you have own
struct
, you could have own convert-to-string function.Another example with a struct :
Be careful when using it,
concatenation with '+' doesn't compile :