繁体   English   中英

如何在golang中实现不同包的接口?

[英]How to implement interface from a different package in golang?

我是golang的初学者,正在尝试接口。 我想将接口保存在一个单独的包中,以便我可以使用它在各种其他包中实现它,也将它提供给其他团队(.a文件),以便他们可以实现自定义插件。 请参阅下面的示例,了解我希望实现的目标。

--- Folder structure ---
gitlab.com/myproject/
                  interfaces/
                            shaper.go
                  shapes/
                        rectangle.go
                        circle.go

---- shaper.go ---
package interfaces

type Shaper interface{

    Area() int

}

如何确保rectangle.go实现整形器接口? 我明白go隐式实现接口,这是否意味着rectangle.go自动实现shaper.go即使它在不同的包中?

我尝试过如下,但是当我运行gofmt工具时,它会删除导入,因为它未被使用。

--- rectangle.go ---
package shapes

import "gitlab.com/myproject/interfaces"

type rectangle struct{

  length int
  width int
}

func (r rectangle) Area() int {
 return r.length * r.width
}

提前致谢。

关于接口的go wiki中有一个很好的部分

Go接口通常属于使用接口类型值的包,而不是实现这些值的包。 实现包应该返回具体的(通常是指针或结构)类型:这样,可以将新方法添加到实现中而无需进行大量重构。

这也有一个优点,它减少了包之间的耦合(通过不强迫任何人只为界面导入你的包),它通常导致更小的接口(通过允许人们只消耗你将构建的接口的一部分) 。

如果您是新手,我强烈建议您阅读我关联的“Go Code Review Comments”维基文章,如果您还有更多时间也可以使用Effective Go 快乐的黑客!

假设您有一个使用Shaper的函数。 您可以使用rectangle测试该函数,并通过这样做来确保实现:

func DoStuff(s Shaper) {
    s.Area()
}

func TestDoStuff(t *testing.T) {
    var s Shaper = rectangle{length: 5, width: 3}
    DoStuff(s)
    // assertion
}

如果rectangle没有实现Shaper ,你会收到如下错误:

cannot use rectangle literal (type rectangle) as type Shaper in assignment:
rectangle does not implement Shaper (missing Area method)

有效的去

Interfaces in Go provide a way to specify the behavior of an object: if something can do this, then it can be used here.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM