从不同的包golang实现接口
Implementing interface from different package golang
我在尝试实现在 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
是否可以从不同的包中实现接口?
谢谢!
问题是您的 do
函数没有从 implementations
包中导出,因为它以小写字母开头。因此从main
包的角度来看,变量interfaceImpl
没有实现接口,因为它看不到do
函数。
将您的接口函数重命名为大写 Do
以解决问题。
我在尝试实现在 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
是否可以从不同的包中实现接口?
谢谢!
问题是您的 do
函数没有从 implementations
包中导出,因为它以小写字母开头。因此从main
包的角度来看,变量interfaceImpl
没有实现接口,因为它看不到do
函数。
将您的接口函数重命名为大写 Do
以解决问题。