该strings.Join函数仅接受字符串切片:
s := []string{"foo", "bar", "baz"}
fmt.Println(strings.Join(s, ", "))
Run Code Online (Sandbox Code Playgroud)
但是能够传递实现ToString()函数的任意对象会很好.
type ToStringConverter interface {
ToString() string
}
Run Code Online (Sandbox Code Playgroud)
在Go中是否存在类似的东西,或者我是否必须int使用ToString方法来装饰现有类型并编写包装器strings.Join?
func Join(a []ToStringConverter, sep string) string
Run Code Online (Sandbox Code Playgroud)
zzz*_*zzz 151
将String() string方法附加到任何命名类型并享受任何自定义"ToString"功能:
package main
import "fmt"
type bin int
func (b bin) String() string {
return fmt.Sprintf("%b", b)
}
func main() {
fmt.Println(bin(42))
}
Run Code Online (Sandbox Code Playgroud)
游乐场:http://play.golang.org/p/Azql7_pDAA
产量
101010
Run Code Online (Sandbox Code Playgroud)
小智 12
当你拥有自己的时候struct,你可以拥有自己的转换为字符串功能.
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]
}
Run Code Online (Sandbox Code Playgroud)
另一个结构体的例子:
package types
import "fmt"
type MyType struct {
Id int
Name string
}
func (t MyType) String() string {
return fmt.Sprintf(
"[%d : %s]",
t.Id,
t.Name)
}
Run Code Online (Sandbox Code Playgroud)
使用它时要小心,
与“+”的连接 不会编译:
t := types.MyType{ 12, "Blabla" }
fmt.Println(t) // OK
fmt.Printf("t : %s \n", t) // OK
//fmt.Println("t : " + t) // Compiler error !!!
fmt.Println("t : " + t.String()) // OK if calling the function explicitly
Run Code Online (Sandbox Code Playgroud)