我在尝试实现接口时遇到了一些问题,该接口在golang的另一个包中定义。我对下面的问题只做了最小的重述
接口:
package interfaces
type Interface interface {
do(param int) int
}
实施:
package implementations
type Implementation struct{}
func (implementation *Implementation) do(param int) int {
return param
}
Main.go:
package main
import (
"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
是否可以从其他包中实现接口?
谢谢!
答案 0 :(得分:4)
问题在于您的do
函数没有从implementations
包中导出,因为它以小写字母开头。因此,从main
包的角度来看,变量interfaceImpl
无法实现接口,因为它看不到do
函数。
将接口函数重命名为大写Do
,以解决问题。