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 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值