【发布时间】:2021-12-31 03:24:51
【问题描述】:
我对 golang 很陌生,我正在尝试了解封装在 go 中的真正工作原理。
我有以下结构
-- package a
-a_core.go
-a.go
-models.go
-- main.go
在 models.go 中,我有用于 api 调用的请求和响应的结构,
a.go 有一个空结构,它是私有的和一个公共接口,我想用各种方法公开它
a_core.go 只是有一些将在我的接口实现中调用的业务逻辑
然后,我有一个 main.go,我只是在其中调用公共接口。
a.go 中的代码
package a
type myFunction struct{}
type MyFunc interface {
Create(myData *MyData) (*MyData, error)
Fetch(test string)
Delete(test string)
}
//Concrete implementations that can be accessed publicly
func (a *myFunction) Create(data *MyData) (*MyData, error) {
return nil, nil
}
func (a *myFunction) Fetch(test string) {
}
func (a *myFunction) Delete(test string) {
}
在 main.go 中,我首先调用接口创建带有值的 MyData 指针
data := &a.MyData{
/////
}
result, err := a.MyFunc.Create(data)
执行此操作时出现以下错误,
调用 a.MyFunc.Create 时的参数太少
不能将数据(*a.MyData 类型的变量)用作 a.MyFunc.Create 参数中的 a.MyFunc 值:缺少方法 CreatecompilerInvalidIfaceAssign
请问我做错了什么?
【问题讨论】:
-
这个playground example 可能会帮助您了解接口的工作原理(tour 有更多信息)。
-
@Brits 非常感谢你
标签: go visual-studio-code struct interface