dpwle46882 2017-12-20 14:01
浏览 32
已采纳

使用自定义类型实现接口,而无需导入包

Suppose there's a 3rd party package that makes an interface available:

package giantpackage

type UselessInfo struct {
    wontUse     string
    alsoWontUse string
}

type CoolInterface interface {
    DoSomethingAwesome(ui UselessInfo) (string, error)
}

It seems easy to implement as such:

package main

import giantpackage

type Jedi struct {
    name string
    age  int
}

func (j Jedi) DoSomethingAwesome(ui giantpackage.UselessInfo) (string, error)
    return "Hello world.", nil
}

Assuming:
1) I don't actually use the UselessInfo struct in my DoSomethingAwesome function.
2) The package that I have to import is HUGE.
3) The package that I have to import is no longer maintained, and cannot be modified.

My question:
Is there any way to implement CoolInterface without importing giantpackage?

  • 写回答

1条回答 默认 最新

  • dousi6405 2017-12-20 14:04
    关注

    There is not.

    To implement the giantpackage.CoolInterface, your type must have a method:

    DoSomethingAwesome(giantpackage.UselessInfo) (string, error)
    

    And to have a method that matches this signature, you have to import giantpackage, else using any other type for the parameter, it won't match the required method.

    In your comments you indicated you plan to create a library, and providing an implementation of this interface will be a "nice to have" feature to some of the users of your library.

    Then the recommended way is to create a "core" package of your library which does not contain this interface implementation and thus does not depend on giantpackage. Users of your library that do not need this will only import your "core" package and so they will also not depend on giantpackage.

    Create another "extension" package of your library which will contain the implementation of this interface (and which may also use your "core" package if needed). Users that do need this can import this package as well.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 关于多单片机模块化的一些问题
  • ¥30 seata使用出现报错,其他服务找不到seata
  • ¥35 引用csv数据文件(4列1800行),通过高斯-赛德尔法拟合曲线,在选取(每五十点取1点)数据,求该数据点的曲率中心。
  • ¥20 程序只发送0X01,串口助手显示不正确,配置看了没有问题115200-8-1-no,如何解决?
  • ¥15 Google speech command 数据集获取
  • ¥15 vue3+element-plus页面崩溃
  • ¥15 像这种代码要怎么跑起来?
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection