加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

接口中的构造方法? (在Golang)

发布时间:2020-12-16 09:25:20 所属栏目:大数据 来源:网络整理
导读:如果我有以下接口和结构: package shapetype Shape interface { Area()}type Rectangle struct {}func (this *Rectangle) Area() {}func New() Shape { return Rectangle{}} 那么如何将New()方法(作为构造函数)添加到接口Shape中? 用例是如果我有另一个str
如果我有以下接口和结构:

package shape

type Shape interface {
    Area()
}

type Rectangle struct {
}

func (this *Rectangle) Area() {}

func New() Shape {
    return &Rectangle{}
}

那么如何将New()方法(作为构造函数)添加到接口Shape中?

用例是如果我有另一个struct Square

type Square struct {
    Rectangle
}

然后Square将有一个方法Area().但它不会有New().我的目的是让任何继承Shape的结构都自动具有New()方法.我怎样才能做到这一点?

解决方法

在Go中,无法在Interfaces上创建方法.

而不是为接口创建方法,惯用的方法是创建以接口为参数的函数.在你的情况下,它将采用一个Shape,使用reflect包返回相同类型的New实例:

func New(s Shape) Shape { ... }

另一种可能性是将接口嵌入到struct类型中,而是在struct类型上创建New-method.

游乐场示例:http://play.golang.org/p/NMlftCJ6oK

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读