我是Golang的初学者,并且正在尝试接口。我想将接口放在单独的软件包中,以便我可以在其他各种软件包中使用它来实现它,还可以将其提供给其他团队(.A文件(,以便它们可以实现自定义插件。请参阅下面有关我想实现的目标的示例。
--- Folder structure ---
gitlab.com/myproject/
interfaces/
shaper.go
shapes/
rectangle.go
circle.go
---- shaper.go ---
package interfaces
type Shaper interface{
Area() int
}
如何确保矩形实现塑形接口?我知道GO隐含地实现了接口,这是否表示矩形。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接口通常属于使用接口类型的值的软件包,而不是实现这些值的软件包。实施软件包应返回具体(通常是指针或结构(类型:这样,可以将新方法添加到实施中,而无需大量重构。
这也具有一个优势,它可以减少软件包之间的耦合(通过不强迫任何人仅以接口导入您的软件包(,并且通常会导致较小的接口(通过允许人们仅消耗您所能使用的接口子集已建立(。
如果您是新手,我强烈建议您阅读我链接的Wiki文章的" Go Code Review评论",如果您还有更多时间也有效。快乐黑客!
假设您的功能使用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)
有效GO:
Interfaces in Go provide a way to specify the behavior of an object: if something can do this, then it can be used here.