在一个包中定义的接口(interface)在不同的包中不起作用

标签 interface go

我在包 goQA 中定义了一个简单的接口(interface),并将它与实现该接口(interface)的结构一起使用:

type ReportWriter interface {
    Name() string
    Init(parent ITestManager)
    onManagerStatistics(report *ManagerResult, stats *ReporterStatistics, name, msg string)
}


type MongoReporter struct {
}

func (t *MongoReporter) Name() string {
}

func (t *MongoReporter) Init(parent ITestManager) {
}

func (t *MongoReporter) onManagerStatistics(report *ManagerResult, stats *ReporterStatistics, name, msg string) {
}

然后我可以在示例文件中创建一个变量,一切正常:

var mr goQA.ReportWriter
mr = &goQA.MongoReporter{}

将结构移动到它自己的包 mongo 并导入 goQA 包时出现问题。一切都一样,除了使用包名:

type MongoReporter struct {
}

func (t *MongoReporter) Name() string {
}

func (t *MongoReporter) Init(parent goQA.ITestManager) {
}

func (t *MongoReporter) onManagerStatistics(report *goQA.ManagerResult, stats *goQA.ReporterStatistics, name, msg string) {
}

我尝试像以前一样在示例程序中使用结构:

var mr goQA.ReportWriter
mr = &mongo.MongoReporter{}

出现错误信息:

""""examples\example_mongo1.go:108: 不能在赋值中使用 mongo.MongoReporter 文字(类型 *mongo.MongoReporter)作为 oQA.ReportWriter 类型: *mongo.MongoReporter 没有实现 goQA.ReportWriter(缺少 goQA.onManagerStatistics 方法)有 mongo.onManagerStatistics(*goQA.ManagerResult, *goQA.ReporterStatistics, string, string) 想要 goQA.onManagerStatistics(*goQA.ManagerResult, *goQA.ReporterStatistics, string, string)""""

为什么它说“有 mongo.onManagerStatistics 但想要 goQA.onManagerStatistics?”签名不一样? 为什么不提示 Init() 和 Name() 方法?

将 Name() 字符串方法更改为 Name(i int) 字符串后,错误是

有 Name(int) 字符串 想要 Name() 字符串

没说:

有 mongo.Name(int) 字符串 想要 goQA.Name() 字符串

我不明白这里的错误是什么。看起来不像是实现接口(interface)时的简单错误。

最佳答案

包 B 如何提供一个类型来满足包 A 的接口(interface),而 A 具有未导出的方法?确切地说:不能。您必须使用大写 O 导出 onManagerStatistics

关于在一个包中定义的接口(interface)在不同的包中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23277395/

相关文章:

java - 实现一个类方法继承自两个不同返回类型的接口(interface)

intellij-idea - Idea Intellij 如何从控制台的打印语句导航到行

go - $GOPATH 的最佳位置在哪里?

http - Go 客户端程序生成大量处于 TIME_WAIT 状态的套接字

c# - 在接口(interface)中定义类实现

java - 更好地理解接口(interface)

java - NoClassDefFoundError

azure - 在 Azure 存储元数据中使用国际字符?

mongodb - 执行将我连接到mongodb数据库的函数时出现问题

spring - Spring CrudRepository 中方法的 AspectJ 切入点