[英]How To Convert Bytes Into Strings In Go[lang]
我是 Go 的新手並嘗試進行縱梁練習,但我無法在 Go 中將bytes
轉換為string
。 我查看並找到了一個解決方案string(i[:])
但這不起作用。 下面是我的完整代碼
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)
}
}
預期的結果是
loopback: 127.0.0.1
googleDNS: 8.8.8.8
任何幫助將非常感激。
干杯,DD。
將 4 字節數組轉換為“點四邊形”的“正確”方法would be to use the in-built
網絡 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)
}
將String()
更改為此
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. 而在 Golang integer 類型不能直接轉換為字符串沒有 function 像strconv.Itoa()
或fmt.Sprintf('%d', int)
你的代碼可以像
func (i IPAddr) String() string {
return return fmt.Sprintf("%v.%v.%v.%v", i[0], i[1], i[2], i[3])
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.