I am new in Go and trying to do Stringers exercise but I am unable to convert bytes
to string
in Go. I looked and found a solution string(i[:])
but that is not working. Below is my complete code
package main
import (
"fmt"
)
type IPAddr [4]byte
func (i IPAddr) String() string {
// not sure how to turn bytes into string ?
// expected result: from {127, 0, 0, 1} -> 127.0.0.1
return string(i[:])
}
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)
}
}
expected result is
loopback: 127.0.0.1
googleDNS: 8.8.8.8
any help would be really appreciated.
CHeers, DD.
The "right" way to convert a 4-byte array to a 'dotted quad would be to use the in-built
net` package:
package main
import (
"fmt"
"net"
)
func main() {
octets := []byte{123, 45, 67, 89}
ip := net.IP(octets)
dottedQuad := ip.To4().String()
fmt.Printf("%v is %s\n", octets, dottedQuad)
}
change String()
to this
func (i IPAddr) String() string {
// return fmt.Sprintf("%d.%d.%d.%d", i[0], i[1], i[2], i[3])
var res string
for _, v := range i {
res += strconv.Itoa(int(v)) + "."
}
return res[:len(res)-1]
}
You can't just output the UTF-8 encoded value as the string the 127 take as the UTF-8 value not the string so you should change the integer to the string first. And in Golang integer type can not directly transform to string without function like strconv.Itoa()
or fmt.Sprintf('%d', int)
your code can be like
func (i IPAddr) String() string {
return return fmt.Sprintf("%v.%v.%v.%v", i[0], i[1], i[2], i[3])
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.