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

huangapple go评论78阅读模式
英文:

How use interface in function, where argument is another interface, that have same list of functions?

问题

我在函数参数中遇到了接口的问题。

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

Playground

如果我想在函数Hello中使用接口A,我该如何重构这段代码呢?谢谢!

英文:

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

得分: 2

如果你想要在任何接受接口B的地方都能使用接口A,那么A必须实现B中定义的所有方法。这包括New() BB()

实际上,你可以这样在A中嵌入B

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

你可以在这里找到一个可工作的示例。

请注意,在我的示例中,我仍然需要在AS结构体中实现AB的所有方法。

我还必须重命名这两个New()函数。在Go语言中,即使两个函数的返回值不同,也不能在同一个包中有相同的函数名。

一般来说,在接口中不需要提供构造函数,因为可以在没有构造函数的情况下创建结构体。

英文:

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.

huangapple
  • 本文由 发表于 2017年8月16日 00:40:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/45697430.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定