dtjpz48440
2017-10-08 01:02
浏览 33
已采纳

去接收器隐式指针转换不起作用

I'm learning Go, and I was following the go tour.

In the exercise about Stringer, here, Implementing the function with a *IPAddr receiver doesn't seem to work, which the go tour describes as should work.

package main

import "fmt"

type IPAddr [4]byte

// TODO: Add a "String() string" method to IPAddr.
func (ip *IPAddr) String() string {
    return fmt.Sprintf("%v.%v.%v.%v", ip[0], ip[1], ip[2], ip[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)
    }
}

Output is:

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

But changing String() string to func (ip IPAddr) from func (ip *IPAddr) gives the correct output:

loopback: 127.0.0.1
googleDNS: 8.8.8.8

Why is that?

图片转代码服务由CSDN问答提供 功能建议

我正在学习围棋,而我正在参加围棋之旅。

在关于Stringer的练习中,此处,使用* IPAddr接收器实现该功能不会 似乎行得通,这次旅行之旅将其描述为应该行之有效的。

 包main 
 
import“ fmt” 
 
type IPAddr [4] byte 
 
 // TODO:向其中添加“ String()字符串”方法 IPAddr。
func(ip * IPAddr)String()string {
 return fmt.Sprintf(“%v。%v。%v。%v”,ip [0],ip [1],ip [2],  ip [3])
} 
func main(){
 hosts:= map [string] IPAddr {
“ loopback”:{127,0,0,1},
“ googleDNS”:{8,  8、8、8},
} 
为名称,ip:=范围主机{
 fmt.Printf(“%v:%v 
”,名称,ip)
} 
} 
 <  / code>  
 
 

输出为:

 回送:[127 0 0 1] 
googleDNS:[8 8 8 8] 
    
 
 

,但是将 String()字符串 func(ip * IPAddr)更改为 func(ip IPAddr)给出正确的输出:

 回送:127.0.0.1 
googleDNS:8.8.8.8 
   
 
 <  p>为什么? 
 
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongzi3434 2017-10-08 01:17
    已采纳

    The implicit conversion means that you can call the function on either a value, or pointer, but it does not satisfy the implementation of an interface. If you implement an interface with a pointer receiver, the pointer must be used in the function call.

    The code below shows the *IPAddr used with the Stringer interface, and an IPAddr used with the new foo() function (also implemented with a pointer receiver):

    package main
    
    import "fmt"
    
    type IPAddr [4]byte
    
    // TODO: Add a "String() string" method to IPAddr.
    func (ip *IPAddr) String() string {
        return fmt.Sprintf("%v.%v.%v.%v", ip[0], ip[1], ip[2], ip[3])
    }
    
    func (ip *IPAddr) foo() string {
        return "bar"
    }
    
    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.Println(ip.foo())
        }
    }
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dongxianghui3709 2017-10-08 01:17

    Implementing func (ip IPAddr) String() will work for both IPAddr and *IPAddr types.

    Implementing func (ip *IPAddr) String will only work for *IPAddr.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题