dqeq885710 2015-10-20 20:11
浏览 14
已采纳

在“ A Go Tour”中,如何修改接口以要求在指针上有方法?

In "A Go Tour" on Interfaces we have this interface:

type Abser interface {
    Abs() float64
}

It is explained that this type, Vertex, does not satisfy the above Abser:

type Vertex struct {
    X, Y float64
}

func (v *Vertex) Abs() float64 {
    return math.Sqrt(v.X*v.X + v.Y*v.Y)
}

How do I modify the Abser interface so that Vertex satisfies it?

(It's okay if it no longer satisfies MyFloat in the full example.)

Before I posted this question I spent some hours searching and head scratching but after posting I found another SO question which covers similar material and may be of help to other neophytes:

"method requires pointer receiver” in Go Programming Language

  • 写回答

1条回答 默认 最新

  • dongyi1429 2015-10-20 20:17
    关注

    You're slightly confused about what is implementing what. In this case, *Vertex is implementing Abser and not Vertex to make it so Vertex does as well, you have to change the receiving type on your implementation of Abs so that it's not a pointer;

    func (v Vertex) Abs() float64 {
        return math.Sqrt(v.X*v.X + v.Y*v.Y)
    } // Vertex implementing Abser here
    

    So the way you're phrasing the question is a bit misleading. The interface requires no change and should receive none. Just fyi, you can have both *Vertex and Vertex implement the interface by using the method I put above as well as the one you already have.

    This is a point that often trips people up in Go. When you declare func (t SomeType) you're specifying the receiving type, if this is a pointer like (t *SomeType) then the thing implementing the interface is not SomeType but rather *SomeType. This differs a little from other languages where the method is implemented by the class and it doesn't matter if you're working with a reference or a value. In Go, the class doesn't implement the method, you specify the 'receiving type' - the thing that the method can be called on - that first argument actually gets pushed on the stack and used the same as an argument passed into a method, the distinction is only relevant for compilation (interface fulfillment really is the only reason to have the feature afaik). So, to summarize, if you want Vertex to implement the Abser interface which features a single method Abs() float64 then you need to define the function as func (v Vertex) Abs() float64 { ... }.

    Just for the sake of having clear readable code I recommend not having the interface defined for both pointers and values... You can work around that using the address of or dereference operator.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面