[轉]Golang之struct類型

來源:互聯網
上載者:User

標籤:

http://blog.chinaunix.net/xmlrpc.php?r=blog/article&uid=22312037&id=3756923

一、struct
        Go語言中,也有struct,定義與C語言類似,舉例說明如下:
        type person struct {
            name string
            age int
        }
        上面就聲明了一個結構體person,包含兩個欄位。可以如下來使用這個struct:
        var P person        //P現在就是person類型的變數了
        P.name = "shicq"    //賦值給P的name屬性
        P.age = 31            //賦值給P的age屬性
        fmt.Printf("The person‘s name  is %s", P.name)    //訪問P的name屬性
        除了上面這種P的聲明使用之外,還有兩種聲明使用方式:
        (1)按照順序提供初始化值。
        P := person("Li Lei", 25)
        (2)通過field:value的方式初始化,這樣可以任意順序。
        P := person(age:24, name:"Han Meimei")      

二、匿名欄位
        前文介紹了如何定義一個struct,定義的時候是欄位名與其類型一一對應,實際上Go語言支援只提供類型,而不寫欄位名的方式,也就是匿名欄位,或稱為嵌入欄位。當匿名欄位是一個struct的時候,那麼這個struct所擁有的全部欄位都被隱式地引入了當前定義的這個struct。下面舉例說明之:
        type Human struct {
            name string
            age int
        }
        type Student struct {
            Human        //匿名欄位,那麼預設Student就包含了Human的所有欄位
            speciality string
        }
        //初始化Student
        mark := Student(Human{"shicq", 31}, "Computer Science")
        //訪問相應欄位
        fmt.Println("His name is ", mark.name)
        fmt.Println("His age is ", mark.age)
        fmt.Println("His speciality is ", mark.speciality)
        我們看到Student訪問屬性age和name的時候,就像訪問自己所擁有的欄位一樣。當然Student也能通過訪問Human來訪問這兩個欄位:
        mark.Human = Human{"shicq", 31}
        mark.Human.age -= 1
        不僅僅是struct欄位,所有內建類型和自訂類型都可以作為匿名欄位,比如slice。
        如果human中有一個叫做phone的欄位,而student也有一個叫做phone的欄位,該當如何呢? 
        Go語言中最外層的優先訪問,也就是當通過student.phone訪問的時候,訪問的是student裡面的欄位,而不是human裡面的欄位。
        這就允許我們可以重載通過匿名欄位繼承的一些欄位,當然如果想訪問重載後對應的匿名型別裡的欄位,可以通過匿名欄位名來訪問:
        type Human struct {
            name string
            age int
            phone string    //Human類型擁有的欄位
        }
        type Employee struct {
            Human        //匿名欄位Human
            speciality string
            phone string        //僱員的phone欄位
        }
        Bob := Employee{Human{"Bob", 24, "777-444-xxxx"}, "Designer", "333-222"}
        fmt.Println("Bob‘s work phone is ", Bob.phone)                    
        fmt.Println("Bob‘s personal phone is ", Bob.Human.phone)        //訪問Human的phone欄位




[轉]Golang之struct類型

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.