go - 通过嵌入类型返回接口
问题描述
我需要返回一个接口。但我收到一个错误:
cannot use B literal (type B) as type K in return argument:
B does not implement K (missing Check method)
我想当我嵌入类型时,我得到了所有内部类型和接口类型的方法
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()
推荐阅读
- ansible - Ansible Tower:将额外变量从一个工作流模板传递到另一个
- oauth - 在 DocuSign 中使用 JWT 时无法在会话错误中找到 OAuth 发起程序参数 - Servicenow 集成
- gatsby - Gatsby - Prismic 站点在构建时中断
- python - .exe 上的图表与 Spyder 上的图表看起来不一样
- javascript - React.js:如何仅在观看滚动位置后调用函数
- python - 将数据框导入另一个脚本
- python - 如何循环更新图形?
- anylogic - 如何在代理群体中创建代理群体
- javascript - 如何通过 JQuery 修复 CWE 117(不正确的日志输出中和)
- regex - 匹配以某个单词开头且不以空格分隔的每个单词中某个字符的所有实例