我在尝试实现接口时遇到了一些问题,该接口在golang的另一个包中定义。我对下面的问题做了一个最小的重新表达

接口:

1
2
3
4
5
package interfaces

type Interface interface {
    do(param int) int
}

实施:

1
2
3
4
5
6
7
package implementations

type Implementation struct{}

func (implementation *Implementation) do(param int) int {
    return param
}

Main.go:

1
2
3
4
5
6
7
8
9
10
11
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{}
}

错误消息:

1
2
3
4
5
6
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

是否可以从其他包中实现接口?

谢谢!

  • 值得注意的是,采用一种方法interface的API可以重写为采用函数类型。请参阅stackoverflow.com/a/63557675/12817546。

问题是您的do函数没有从implementations包中导出,因为它以小写字母开头。因此,从main包的angular来看,变量interfaceImpl无法实现接口,因为它看不到do函数。

将接口函数重命名为大写do,以解决此问题。