《go語言程式設計》學習(十)

來源:互聯網
上載者:User

標籤:

一,自訂類型

這部分看來很久,感覺很難懂,很難掌握關鍵點。有以下幾個概念:

介面嵌入,結構體的彙總與嵌入(嵌入值,嵌入帶方法帶匿名值,嵌入介面),自由組合的相互獨立介面。

嵌套不是繼承。

基本的嵌入就不詳細說了,這種嵌入帶來的效果就是A中嵌入了B,則A相當於自己定義了B點全部內容。

自由組合的相互獨立介面,相對於有層次的嵌套,要靈活的多,而且無需保持階層,可以自由的添加其他介面。

介面嵌入,還是用一段代碼說吧

type optioner interface {Name() stringIsValid() bool}type OptionCommon struct {ShortName stringLongName string}type FloatOption struct {Optioner  //匿名欄位,(介面嵌入,需要具體的類型)Value float64}type GenericOption struct {OptionCommon  //匿名欄位,嵌入}func (option GenericOption) Name() string {return name(option.ShortName, option.LongName)}func (option GenericOption) IsValid() bool {return true}func main(){sizeOption := FloatOption{    GenericOption{OptionCommon{"s","size"}},12.3}}

注意看這段代碼,定義floatoption的時候,是嵌入的介面,使用的時候,要顯式的賦予一個值來滿足該介面。(介面說抽象的,無法預設初始化為0)

《go語言程式設計》學習(十)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.