3 回答

TA貢獻1818條經驗 獲得超8個贊
您所指的不是接口(它允許將對象作為該接口傳遞,僅僅是因為該對象是所有接口方法的接收器)。
在這里,任何類型都可以滿足空值interface{}' Shape,這在這里沒有用。
更多關于類型嵌入(例如使用匿名類型結構):
這將促進共同項目edgesCount這兩個結構。
正如規范所提到的:
字段或方法f在一個匿名字段的struct x被稱為促進如果x.f是一個合法的選擇器,它表示字段或方法f。
請參閱此示例:
type Shape struct {
edgesCount int
}
type Square struct {
Shape
}
type Triangle struct {
Shape
}
func NewSquare() *Square {
return &Square{
Shape{edgesCount: 4},
}
}
func NewTriangle() *Triangle {
return &Triangle{
Shape{edgesCount: 3},
}
}
func main() {
fmt.Printf("Square %+v\n", NewSquare())
fmt.Printf("Triangle %+v\n", NewTriangle())
}
輸出:
Square &{Shape:{edgesCount:4}}
Triangle &{Shape:{edgesCount:3}}

TA貢獻1998條經驗 獲得超6個贊
Go 不是面向對象的語言,這些字段是內部字段,因為它們以小寫字母開頭。相反,嘗試這樣的事情:
type Shape interface {
EdgeCount() int
}
type Square struct {
edgesCount int
}
func (s Square) EdgeCount() int {
return s.edgesCount
}
type Triangle struct {
edgesCount int
}
func (t Triangle) EdgeCount() int {
return t.edgesCount
}
現在您可以在任一類型的對象上使用 EdgeCount 函數執行操作,因為它們都實現了 Shape 接口。
func IsItSquare(s Shape) bool {
// If it has 4 sides, maybe
return s.EdgeCount == 4
}
但是您仍然需要使用獨立的 New 函數創建不同類型的形狀,或者只是通過字面聲明它們。
// Obviously a contrived example
s := Triangle{edgesCount: 3}

TA貢獻1895條經驗 獲得超7個贊
接口僅對方法進行分組,因為它們的目的是定義行為,非常類似于其他語言(例如,請參閱Java 接口)。
您正在尋找的是類似于代碼繼承的東西,它在 Go 中不存在。但是,您可以通過struct embedding獲得類似的東西:
Go 沒有提供典型的、類型驅動的子類化概念,但它確實有能力通過在結構或接口中嵌入類型來“借用”實現的片段。
因此,您可以通過執行以下操作(播放鏈接)來獲得您想要的內容:
type Shape struct {
edgeCount int
}
func (s Shape) EdgeCount() int {
return s.edgeCount
}
type Square struct {
Shape
}
type Triangle struct {
Shape
}
func main() {
sq := Square{Shape{edgeCount: 4}}
tr := Square{Shape{edgeCount: 3}}
fmt.Println(sq.EdgeCount())
fmt.Println(tr.EdgeCount())
}
- 3 回答
- 0 關注
- 213 瀏覽
添加回答
舉報