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.

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

报告相同问题?

悬赏问题

  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?