In many languages, you can easily convert any data type to a string by concatenating it to a string, or by using a type conversion expression. However, if you try to do something that seems obvious in Go (such as converting an int to a string), you are unlikely to get the desired effect.
For example:
string(120)
Copy the code
What do you expect to return? If you have experience with other programming languages, most people’s guess is “123.” In contrast, in Go the above conversion would yield something like “E”, which is not what we want at all. Because string() converts bytes or numbers directly to utF-8 representations of characters.
So the correct way to convert a byte or int value toa numeric string representation in Go is to use strconv package methods, such as strconv.itoa.
/ / return strconv. Itoa (120)"120"
Copy the code
In the following example, try changing strconv.Itoa to string to see what output you get.
package main
import (
"fmt"
"strings"
"strconv"
)
type IPAddr [4]byte
func (p IPAddr) String() string {
var ipParts []string
for _, 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)
}
}
Copy the code