亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

理解 Go 中的接口

理解 Go 中的接口

Go
至尊寶的傳說 2021-09-13 10:23:27
我試圖了解接口在 Go 中是如何工作的。假設我有 2 個結構:package "Shape"type Square struct {   edgesCount int}type Triangle struct {   edgesCount int}現在我創建一個Shape界面:type Shape interface {}為什么我不能指定Shape接口有一個egdesCount屬性?接口是否只應該重新組合方法?我面臨的另一個問題是共享功能。不可能想出這樣的事情:func New() *Shape {  s:=new(Shape)  s.edgesCount = 0  return s}這比必須重寫完全相同的代碼要好得多:func New() *Square {  s:=new(Square)  s.edgesCount = 0  return s}func New() *Triangle {  s:=new(Triangle)  s.edgesCount = 0  return s}(這也帶來了問題,因為我無法重新聲明我的New功能......)非常感謝您的幫助
查看完整描述

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}}


查看完整回答
反對 回復 2021-09-13
?
米琪卡哇伊

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}


查看完整回答
反對 回復 2021-09-13
?
人到中年有點甜

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())

}


查看完整回答
反對 回復 2021-09-13
  • 3 回答
  • 0 關注
  • 213 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號