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条)

报告相同问题?

悬赏问题

  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥15 复杂网络,变滞后传递熵,FDA