gpt4 book ai didi

go - 通过嵌入类型返回接口(interface)

转载 作者:行者123 更新时间:2023-12-01 22:45:28 24 4
gpt4 key购买 nike

我需要返回一个接口(interface)。但我收到一个错误:

cannot use B literal (type B) as type K in return argument:
B does not implement K (missing Check method)

我想当我嵌入类型时,我得到了所有内部类型和接口(interface)类型的方法
package main

import (
"fmt"
)

type K interface {
Check()
}

type A struct {
A string
}

type B struct {
B A
}

func (a A) Check() {
fmt.Println(a.A)
}

func newB(a A) K {
return B{B: a}
}

func main() {
a := A{A: "A struct"}
b := newB(a)

b.Check()

}

如何解决这个问题呢?

最佳答案

这不是嵌入:

type B struct {
B A
}

有了以上内容,您有:
var b B
b.B.Check()

这是嵌入:
type B struct {
A
}

有了以上内容,您有:
var b B
b.Check()

你还有:
b.A.Check()

关于go - 通过嵌入类型返回接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58426071/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com