ToString () in Go

The strings.Join function accepts only fragments of strings:

 s := []string{"foo", "bar", "baz"} fmt.Println(strings.Join(s, ", ")) 

But it would be nice to be able to pass arbitrary objects that implement the ToString() function.

 type ToStringConverter interface { ToString() string } 

Is there something like this in Go, or do I need to decorate existing int types with ToString methods and write a wrapper around strings.Join ?

 func Join(a []ToStringConverter, sep string) string 
+48
tostring go
Nov 06
source share
3 answers

Attach the String() string method to any named type and use any custom ToString function:

 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




Exit

 101010 
+97
Nov 06
source share

When you have your own struct , you can have your own string conversion function.

 package main import ( "fmt" ) type Color struct { Red int `json:"red"` Green int `json:"green"` Blue int `json:"blue"` } func (c Color) String() string { return fmt.Sprintf("[%d, %d, %d]", c.Red, c.Green, c.Blue) } func main() { c := Color{Red: 123, Green: 11, Blue: 34} fmt.Println(c) //[123, 11, 34] } 
+8
Oct 21 '15 at 6:31
source share

I prefer something like the following:

 type StringRef []byte func (s StringRef) String() string { return string(s[:]) } … // rather silly example, but ... fmt.Printf("foo=%s\n",StringRef("bar")) 
-four
Dec 26 '14 at 12:47
source share



All Articles