在许多语言中,你可以轻松地将任何数据类型转换为字符串,只需将其与字符串连接,或者使用类型转换表达式即可。但是,如果你在Go中尝试执行似乎很明显的操作(例如将int转换为字符串),你不太可能获得预期的效果。

比如下面:

string(120)
string()
strconvstrconv.Itoa
strconv.Itoa(120)// 返回"120"
strconv.Itoastring
package main
import ("fmt""strings""strconv"
)
type IPAddr [4]byte
func (p IPAddr) String() string {var ipParts []stringfor _, item := range p {ipParts = append(ipParts, strconv.Itoa(int(item)))}return strings.Join(ipParts, ".")
}
func main() {hosts := map[string]IPAddr{"loopback":  {127, 0, 0, 1},"googleDNS": {8, 8, 8, 8},}for name, ip := range hosts {fmt.Printf("%v: %v\n", name, ip)}
}

原文链接里有完整代码,如果访问不了Go Playground可以自己下载下来在本地试一下。