duanniwu7730 2017-08-15 16:40
浏览 10

如何在函数中使用接口,其中参数是另一个具有相同函数列表的接口?

I have trouble with interfaces in function arguments.

package main

import (
    "fmt"
)

type A interface {
    New() A
    B()
    C()
}

type B interface {
    New() B
    B()
}

type AS struct {}
func (AS) New() A {
    return AS{}
}

func (AS) B() {}
func (AS) C() {}

func Hello(b B) {
    b.New()
}

func main() {
    fmt.Println("Hello, playground")

    as := AS{}
    a := A(as)
    Hello(a)
}

I've got this error:

tmp/sandbox293137995/main.go:35: cannot use a (type A) as type B in argument to Hello:
A does not implement B (wrong type for New method)
    have New() A
    want New() B

Playground

How can I refactor this code, if I want use interface A in function Hello? Thanks!

  • 写回答

1条回答 默认 最新

  • doujuxin7392 2017-08-15 17:16
    关注

    If you wanted to able to use interface A anywhere that interface B is accepted, A has to implement all the methods defined in B. So that includes New() B and B().

    Essentially, you can embed B in A like this:

    type A interface {
      NewA() A
      C()
      B
    }
    

    You can find a working example here.

    Notice that in my example, I still have to implement all the methods of both A and B in the AS struct.

    I also have to rename the 2 New() functions. In Go, you can't have 2 functions in the same package with the same name, even though their return values are different.

    In general, you don't need to provide constructors in interface, because structs can be created without them.

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度