为什么我不能用主包中的方法集合调用接口
Why can't I call an interface with a collection of methods from the main package
我是 golang 的新手,我正在尝试了解封装在 go 中是如何工作的。
我有以下结构
-- package a
-a_core.go
-a.go
-models.go
-- main.go
在 models.go 中,我有一个 api 调用的请求和响应结构,
a.go 有一个空结构,它是私有的,还有一个 public 接口,我想用各种方法公开它
a_core.go 只是有一些业务逻辑将在我的接口实现中调用
然后,我有一个 main.go,我只是调用 public 接口。
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
请问我做错了什么?
这是一个例子
请注意,大写的名称是 public,小写的名称是私有的(请参阅 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")
}
我是 golang 的新手,我正在尝试了解封装在 go 中是如何工作的。
我有以下结构
-- package a
-a_core.go
-a.go
-models.go
-- main.go
在 models.go 中,我有一个 api 调用的请求和响应结构,
a.go 有一个空结构,它是私有的,还有一个 public 接口,我想用各种方法公开它
a_core.go 只是有一些业务逻辑将在我的接口实现中调用
然后,我有一个 main.go,我只是调用 public 接口。
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
请问我做错了什么?
这是一个例子
请注意,大写的名称是 public,小写的名称是私有的(请参阅 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")
}