从不同的包golang实现接口

时间:2018-08-02 08:38:55

标签: go interface package implementation

我在尝试实现接口时遇到了一些问题,该接口在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

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

谢谢!

1 个答案:

答案 0 :(得分:4)

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

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