我正在官方的“A Tour of Go”页面上执行一些任务。我已经定义了一个自定义类型,该类型为.IPAddrbyte[4]假设类型的值为 。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贡献1866条经验 获得超5个赞
通过使用字符串转换,值将以一种您不需要的方式进行强制转换。您可以注意到 54 打印为 6,因为 ascii 值 54 对应于“6”。
下面是使用 fmt 获取预期结果的方法。
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 关注
- 102 浏览
添加回答
举报
0/150
提交
取消