我对 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 atype myFunction struct{}type MyFunc interface { Create(myData *MyData) (*MyData, error) Fetch(test string) Delete(test string)}//Concrete implementations that can be accessed publiclyfunc (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.MyFunc.Create 的参数中使用数据(*a.MyData 类型的变量)作为 a.MyFunc 值:缺少方法 CreatecompilerInvalidIfaceAssign请问我做错了什么?
1 回答
三国纷争
TA贡献1804条经验 获得超7个赞
这是一个示例
请注意,大写的名称是公共的,小写的是私有的(请参阅https://tour.golang.org/basics/3)
./go-example/main.go
package main
import "go-example/animal"
func main() {
var a animal.Animal
a = animal.Lion{Age: 10}
a.Breathe()
a.Walk()
}
./go-example/animal/animal.go
package animal
import "fmt"
type Animal interface {
Breathe()
Walk()
}
type Lion struct {
Age int
}
func (l Lion) Breathe() {
fmt.Println("Lion breathes")
}
func (l Lion) Walk() {
fmt.Println("Lion walk")
}
- 1 回答
- 0 关注
- 167 浏览
添加回答
举报
0/150
提交
取消
