douhuan9289 2018-09-09 03:00
浏览 23
已采纳

使用值或指针接收器实现Stringer接口[重复]

This question already has an answer here:

I tried to implement the Stringer interface on my type as follow:

package main

import (
    "fmt"
)

type IPAddr [4]byte

// TODO: Add a "String() string" method to IPAddr.
func (o IPAddr) String() string {
    return fmt.Sprintf("%v.%v.%v.%v",  o[0], o[1], o[2], o[3])
}

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
", name, ip)
        fmt.Printf("%v
",  ip.String())
    }
}

In the code above, I used a value receiver to implement the String() method. The Printf recognised my implementation and called the correct String function on my type.

Output:

googleDNS: 8.8.8.8
8.8.8.8
loopback: 127.0.0.1
127.0.0.1

Then I updated my code to use pointer receiver:

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

The output of the updated code:

loopback: [127 0 0 1]
127.0.0.1
googleDNS: [8 8 8 8]
8.8.8.8

The Printf method didn't call my String method anymore. The output told me that Printf use the default String method of the type. However, when I called ip.String(), my method was used.

Can someone explain to me this behaviour, please? As far as I know, we can implement methods of interfaces by both value and pointer receivers.

Thank you.

</div>
  • 写回答

2条回答 默认 最新

  • dsbezji539113152 2018-09-09 04:05
    关注

    The %v conversion specifier will read any method satisfying the Stringer interface. For this to happen, however, that method must exist in the method set of the value.

    For a value of type T, its method set contains any methods that receive a value of that type T:

    func (t  T) Foo()    //     in the method set of T
    func (t *T) Bar()    // not in the method set of T
    

    For a pointer of type *T, its method set contains both methods that receive a value of type T and a pointer of type *T:

    func (t  T) Foo()    //     in the method set of *T
    func (t *T) Bar()    //     in the method set of *T
    

    In main, you have a value identified as ip with type IPAddr, so the first set of commented code above applies.

    Your first example will work because the method receiver of the String method has type IPAddr.

    In the second example, the method receiver of the String method has type *IPAddr, which means it's not in the method set of ip, which has type IPAddr.

    In summary:

                | String() Method | fmt.Print, fmt.Printf, etc.
     Input Type | Receiver        | calls String() implicitly
     ========== | =============== | ===========================
       *IPAddr  |     IPAddr      | Yes
                |    *IPAddr      | Yes
     ---------- + --------------- + ---------------------------
        IPAddr  |     IPAddr      | Yes
                |    *IPAddr      | No
    

    You might be wondering why this occurs. It turns out that some values might not be addressable, so a method receiver with type *IPAddr can't receive a value that has no address. For example, try executing IPAddr{}.String() with an *IPAddr method receiver. It will fail to compile because a literal value has no address. If you instead used (&IPAddr{}).String(), it would work because now you have a pointer *IPAddr created using &IPAddr{}, and if you used a non-pointer receiver IPAddr, then it would work whether the IPAddr was addressable or not.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料