對此有點困惑。請參閱playground。調用帶父級結構嵌入父項的函數不起作用
我希望去允許你調用一個方法,該方法需要一個嵌入父級的子級的父級。
package main
import (
"fmt"
)
type Parent struct {
A string
}
type Child struct {
Parent
}
func SomeFunction(parent Parent) {
fmt.Println("%v", parent.A)
}
func main() {
child := Child{Parent{A:"test"}}
SomeFunction(child) //prog.go:21: cannot use child (type Child) as type Parent in argument to SomeFunction
}
如果我把這個以「child.Parent」它的工作原理,但在這種情況下,我不能利用該值作爲空接口函數中使用的任何代碼。谷歌搜索出來,發現一個非常有趣和有用的頁面。 Golang concepts from an OOP point of view。任何關於我在這裏失蹤的指導都是值得歡迎的。也許這只是我沒有完全「讓」Golang在這裏。
使用Person界面編寫了一個快速操場https://play.golang.org/p/_JfXyyflP8 ...這是另一個有用的博客文章https://medium.com/@gianbiondi/interfaces-in-go- 59c3dc9c2d98#.7l72q6qwg – poopoothegorilla
謝謝!結束使用一個接口,允許我訪問「父」結構的成員。你是對的,問題在於我試圖按照習慣於在面向對象方式中做事情的方式去做事情,並努力想辦法在Go中完成它們,同時保持DRY。感覺我沒有做正確的事情,因爲我在複製代碼。 – Toby