dongqiao1151 2018-01-27 11:52
浏览 16
已采纳

嵌套接口:X未实现Y(Z方法的类型错误)

In one package I have an interface Repository that has a method GetReporter that returns an interface Reporter. This is used by a function Execute that takes a Repository and gets its Reporter via the GetReporter function.

In another package I have a struct GithubRepository that has a method GetReporter that returns a GithubReporter.

In a third package I want to call the Execute function out of package #1 with a GithubRepository instance.

I am trying to have package 1 and 2 independent of each other, without one importing something from the other. The 3rd package should combine the first two.

Golang returns:

cannot use githubRepository (type GithubRepository) as type Repository in argument to Execute:
    GithubRepository does not implement Repository (wrong type for GetReporter method)
        have GetReporter(string) GithubReporter
        want GetReporter(string) Reporter

Code:

package main

// Package #1

type Repository interface {
  GetReporter(string) Reporter
}

type Reporter interface {
  ChangeStatus(string) error
}

func Execute(r Repository) {
  // Do something with the repository
}

// Package #2

type GithubRepository struct {
}

type GithubReporter struct {
}

func (repo *GithubRepository) GetReporter(sha string) GithubReporter {
 return GithubReporter{}
}

func (reporter *GithubReporter) ChangeStatus(status string) error {
  // Change the status
  return nil
}

// Package #3

func main() {
  githubRepository := GithubRepository{}
  Execute(githubRepository)
}

Go Playground: https://play.golang.org/p/ph0sZnyAC5I

  • 写回答

2条回答 默认 最新

  • douaikuai2715 2018-01-27 13:17
    关注

    It was impossible to make two package independent in such a case. However, with go1.9 and its type alias, this can be done.

    First, as go proverbs say, A little copy is better than a little dependency. You should copy the part of definition of Reporter to package B, and change the signature according to it: func (repo GithubRepository) GetReporter(sha string) Reporter.

    Yet the compiler won't understand that the two interface is the samething. But with the help of type alias, it can be worked around. Change both definition type Reporter interface {...} to type Reporter = interface {...}. And it will compile now.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵