Fonction ToSsortingng () dans Go

La fonction ssortingngs.Join ne prend que des tranches de chaînes:

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

Mais ce serait bien de pouvoir passer des objects arbitraires qui implémentent une fonction ToSsortingng() .

 type ToSsortingngConverter interface { ToSsortingng() ssortingng } 

Y at-il quelque chose comme ça dans Go ou dois-je décorer les types existants comme int avec les méthodes ToSsortingng et écrire un wrapper autour des ssortingngs.Join ?

 func Join(a []ToSsortingngConverter, sep ssortingng) ssortingng 

Attachez une méthode de Ssortingng() ssortingng à n’importe quel type nommé et profitez de toute fonctionnalité “ToSsortingng” personnalisée:

 package main import "fmt" type bin int func (b bin) Ssortingng() ssortingng { return fmt.Sprintf("%b", b) } func main() { fmt.Println(bin(42)) } 

Aire de jeux: http://play.golang.org/p/Azql7_pDAA


Sortie

 101010 

Lorsque vous avez votre propre struct , vous pouvez avoir sa propre fonction de conversion en chaîne .

 package main import ( "fmt" ) type Color struct { Red int `json:"red"` Green int `json:"green"` Blue int `json:"blue"` } func (c Color) Ssortingng() ssortingng { 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] } 

Un autre exemple avec une structure:

 package types import "fmt" type MyType struct { Id int Name ssortingng } func (t MyType) Ssortingng() ssortingng { return fmt.Sprintf( "[%d : %s]", t.Id, t.Name) } 

Soyez prudent lorsque vous l’utilisez,
la concaténation avec ‘+’ ne comstack pas:

 t := types.MyType{ 12, "Blabla" } fmt.Println(t) // OK fmt.Printf("t : %s \n", t) // OK //fmt.Println("t : " + t) // Comstackr error !!! fmt.Println("t : " + t.Ssortingng()) // OK if calling the function explicitly 

Je préfère quelque chose comme ceci:

 type SsortingngRef []byte func (s SsortingngRef) Ssortingng() ssortingng { return ssortingng(s[:]) } … // rather silly example, but ... fmt.Printf("foo=%s\n",SsortingngRef("bar"))