从不同的包golang实现接口

Sim*_*sen 5 implementation interface package go

我在尝试实现接口(在golang的其他程序包中定义)时遇到了一些问题。我对下面的问题做了些微的阐述

接口:

package interfaces

type Interface interface {
    do(param int) int
}
Run Code Online (Sandbox Code Playgroud)

实现方式:

package implementations

type Implementation struct{}

func (implementation *Implementation) do(param int) int {
    return param
}
Run Code Online (Sandbox Code Playgroud)

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{}
}
Run Code Online (Sandbox Code Playgroud)

错误信息:

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
Run Code Online (Sandbox Code Playgroud)

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

谢谢!

gon*_*utz 8

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

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