我在尝试实现接口(在golang的其他程序包中定义)时遇到了一些问题。我对下面的问题做了些微的阐述界面:package interfacestype Interface interface { do(param int) int}执行:package implementationstype Implementation struct{}func (implementation *Implementation) do(param int) int { return param}Main.go:package mainimport ( "test/implementing-interface-in-different-package/implementations" "test/implementing-interface-in-different-package/interfaces")func main() { var interfaceImpl interfaces.Interface interfaceImpl = &implementations.Implementation{}}错误信息:test/implementing-interface-in-different-package./main.go:10:16: cannot use implementations.Implementation literal (type implementations.Implementation) as type interfaces.Interface in assignment: implementations.Implementation does not implement interfaces.Interface (missing interfaces.do method) have implementations.do(int) int want interfaces.do(int) int是否可以从其他包中实现接口?
1 回答
森林海
TA贡献2011条经验 获得超2个赞
问题在于您的do
函数没有从implementations
包中导出,因为它以小写字母开头。因此,从包的角度来看main
,变量interfaceImpl
无法实现接口,因为它看不到do
函数。
重命名您的接口函数为大写字母Do
以解决此问题。
- 1 回答
- 0 关注
- 1036 浏览
添加回答
举报
0/150
提交
取消