我對 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
請問我做錯了什么?
uj5u.com熱心網友回復:
這是一個示例
請注意,大寫的名稱是公共的,小寫的名稱是私有的(請參閱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")
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/362125.html
下一篇:go背景關系取消功能的最佳實踐
