我正在官方的“A Tour of Go”頁面上執(zhí)行一些任務(wù)。我已經(jīng)定義了一個自定義類型,該類型為.IPAddrbyte[4]假設(shè)類型的值為 。IPAddr{127, 2, 0, 1}我需要重寫該方法,以便它以形式而不是的形式打印。String()127.2.0.1[127, 2, 0, 1]這是代碼和我卡住的地方:package mainimport "fmt"type IPAddr [4]bytefunc (p IPAddr) String() string { return string(p[0]) + "." + string(p[1]) + "." + string(p[2]) + "." + string(p[3]) // this here does not work. //Even if I simply return p[0] nothing is returned back.}func main() { a := IPAddr{127, 2, 54, 32} fmt.Println("a:", a)}
1 回答

心有法竹
TA貢獻(xiàn)1866條經(jīng)驗 獲得超5個贊
通過使用字符串轉(zhuǎn)換,值將以一種您不需要的方式進(jìn)行強制轉(zhuǎn)換。您可以注意到 54 打印為 6,因為 ascii 值 54 對應(yīng)于“6”。
下面是使用 fmt 獲取預(yù)期結(jié)果的方法。
package main
import "fmt"
type IPAddr [4]byte
func (p IPAddr) String() string {
return fmt.Sprintf("%d.%d.%d.%d", p[0], p[1], p[2], p[3])
}
func main() {
a := IPAddr{127, 2, 54, 32}
fmt.Println("a:", a)
}
- 1 回答
- 0 關(guān)注
- 104 瀏覽
添加回答
舉報
0/150
提交
取消