dppxp79175 2016-09-01 19:22
浏览 20

斯金格斯的困惑行为?

New to Go, so please bear with me.

I've been looking at the "Tour of Go" pages, and stumbled into something puzzling about Stringers. Consider the exercise at https://tour.golang.org/methods/18

My initial answer was implementing

func (this *IPAddr) String() string {
  return fmt.Sprintf("%d.%d.%d.%d", this[0], this[1], this[2], this[3])
}

however, this is not used f main prints just fmt.Printf("%v: %v ", name, ip). If I change the print to fmt.Printf("%v: %v ", name, ip.String()), then it is used whether the receiver type is *IPAddr or IPAddr).

why is this happening?

  • 写回答

2条回答 默认 最新

  • duandian8110 2016-09-01 19:25
    关注

    Because you're passing an IPAddr value to fmt.Printf, your String() method isn't part of the method set. Your solution works if you pass in a pointer:

    fmt.Printf("%v: %v
    ", name, &ip)
    

    But a general solution is to not use a pointer receiver:

    func (ip IPAddr) String() string {
      return fmt.Sprintf("%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3])
    }
    

    This way the String() method can be used from an IPAddr, which is what you're passing to Printf, or an *IPAddr, which includes the methods of the value receiver.

    评论

报告相同问题?

悬赏问题

  • ¥15 netty整合springboot之后自动重连失效
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击