1-使用net.IP
,像這樣的工作示例代碼:
package main
import "fmt"
import "net"
func main() {
hosts := map[string]net.IP{
"loopback ": {127, 0, 0, 1},
"googleDNS": {8, 8, 8, 8},
}
for name, ip := range hosts {
fmt.Println(name, ":", ip)
}
}
輸出:
loopback : 127.0.0.1
googleDNS : 8.8.8.8
2-使用此:
func (ip IPAddr) String() string {
return strconv.Itoa(int(ip[0])) + "." +
strconv.Itoa(int(ip[1])) + "." +
strconv.Itoa(int(ip[2])) + "." +
strconv.Itoa(int(ip[3]))
}
這樣工作的示例代碼:
package main
import "fmt"
import "strconv"
type IPAddr [4]byte
func (ip IPAddr) String() string {
return strconv.Itoa(int(ip[0])) + "." +
strconv.Itoa(int(ip[1])) + "." +
strconv.Itoa(int(ip[2])) + "." +
strconv.Itoa(int(ip[3]))
}
func main() {
hosts := map[string]IPAddr{
"loopback ": {127, 0, 0, 1},
"googleDNS": {8, 8, 8, 8},
}
for name, ip := range hosts {
fmt.Println(name, ":", ip)
}
}
輸出:
loopback : 127.0.0.1
googleDNS : 8.8.8.8
3-使用strings.Trim(strings.Join(strings.Fields(fmt.Sprint(ip)), "."), "[]")
這樣工作的示例代碼:
package main
import "fmt"
import "strings"
type IPAddr [4]byte
func (ip IPAddr) String() string {
return strings.Trim(strings.Join(strings.Fields(fmt.Sprint([4]byte(ip))), "."), "[]")
}
func main() {
hosts := map[string]IPAddr{
"loopback ": {127, 0, 0, 1},
"googleDNS": {8, 8, 8, 8},
}
for name, ip := range hosts {
fmt.Println(name, ":", ip)
}
}
輸出:
loopback : 127.0.0.1
googleDNS : 8.8.8.8
http://stackoverflow.com/questions/33418107/why-cant-i-do-fmt- sprintfd-DDDA – shaidiren
我發現在計算器同樣的問題: http://stackoverflow.com/questions/33418107/why-cant-i-do-fmt-sprintfd-ddda 但如果有其他的方式來直接調用 – shaidiren
請參閱https: //golang.org/src/net/ip.go#L260 –