【问题标题】:Why can't I call an interface with a collection of methods from the main package为什么我不能用主包中的方法集合调用接口
【发布时间】: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 只是有一些将在我的接口实现中调用的业务逻辑

然后,我有一个 ma​​in.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


【解决方案1】:

这是一个例子
请注意,大写的名称是公开的,小写的是私有的(请参阅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")
}

【讨论】:

  • 我试图从不同的包中引用它。因此,为什么我必须做一个 package.interfacename.methodname 并且这些方法已经在空结构 myFunction 上实现
  • 更新了我的答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-02
  • 1970-01-01
  • 2011-12-09
  • 2013-07-09
  • 2015-02-12
  • 1970-01-01
相关资源
最近更新 更多