Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Go 如何在函数中使用接口,其中参数是具有相同函数列表的另一个接口?_Go - Fatal编程技术网

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

Go 如何在函数中使用接口,其中参数是具有相同函数列表的另一个接口?,go,Go,我对函数参数中的接口有问题 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)

我对函数参数中的接口有问题

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)
}
我有一个错误:

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

如果我想在函数Hello中使用接口,如何重构代码?
谢谢

如果您希望能够在任何接受接口
B
的地方使用接口
A
A
必须实现所有
B
中定义的方法。因此,这包括
New()B
B()

基本上,您可以像这样在
A
中嵌入
B

type A interface {
  NewA() A
  C()
  B
}
你可以找到一个有效的例子

注意,在我的示例中,我仍然必须在
AS
结构中实现
A
B
的所有方法

我还必须重命名2
New()
函数。在Go中,同一个包中不能有两个同名函数,即使它们的返回值不同


通常,您不需要在接口中提供构造函数,因为可以在没有构造函数的情况下创建结构。

在接口上使用
New()
方法的目的是什么?这没有多大意义,这就是你的错误产生的原因。不要试图在围棋中重现经典的OOP。在接口中使用“构造函数”是非常违反直觉的,因为您希望在实例上执行这些方法。在现有实例上调用构造函数是毫无意义的。