go 結構體

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

go 結構體

  • go 結構體
    • 定義
    • 賦值
    • Factory 方法

Go 通過結構體的形式支援使用者自訂類型。

結構體是複合類型(composite types),當需要定義一個類型,它由一系列屬性群組成,每個屬性都有自己的類型和值的時候,就應該使用結構體,它把資料聚集在一起。然後可以訪問這些資料,就好像它是一個獨立實體的一部分。

定義

結構體定義的一般方式如下:

type Identifier struct {    field1 type1    field2 type2    ...}

賦值

結構體是實值型別,因此可以通過 new 來建立。

我們可以使用 . 給欄位賦值:

structname.fieldname = value

同樣的,也可以使用 . 擷取結構體欄位的值:

structname.fieldname

在 Go 語言中這叫 selector。無論變數是一個 結構體類型 還是一個 結構體類型指標,都使用同樣的 selector-notation 來引用結構體的欄位:

type myStruct struct { i int }var v myStruct   // v 是結構體類型變數var p *myStruct  // p 是指向一個結構體類型變數的指標v.ip.i

下面來看一個例子

// rectangle.gopackage recttype Rectangle struct {    length int    width  int}func (r *Rectangle) Set(x, y int) {    r.length = x    r.width = y}func (r *Rectangle) Area() (res int) {    res = r.length * r.width    return}func (r *Rectangle) Perimeter() (res int) {    res = (r.length + r.width) * 2    return}
// main.gopackage mainimport (    "rect"    "fmt")func main() {    rectangle := new(rect.Rectangle)    rectangle.Set(1, 2)    fmt.Println("rectangle is", rectangle)    fmt.Println(rectangle.Area())    fmt.Println(rectangle.Perimeter())}

運行結果

rectangle is &{1 2}26

注意:如果 XX 是一個結構體類型,那麼運算式 new(XX)&XX{} 是等價的。

例如:

type MyStruct struct {    x int    y int}my := new(MyStruct)my.x = 1my.y = 2等價於my2 := &Mystrcut{1, 2}

Factory 方法

你現在突然想,不能讓別人看到我的結構體,我應該把它設為私人的,但是還想讓別人使用我的結構體,該怎麼辦?

為了方便,通常會為類型定義一個工廠,按慣例,工廠的名字以 new 或 New 開頭,它返回一個指向結構體執行個體的指標。形式如下:

// mystruct.gopackage mytype mystruct struct {    ...}func NewMystruct() *mystruct {    m : = new(mystruct)  // 初始化 m    return m}

在其他包裡使用Factory 方法:

// main.gopackage mainimport "my"...wrong : = new(my.mystruct)  // 編譯失敗,mystruct 是私人的right : = my.NewMystruct()  // 執行個體化 mystruct 的唯一方式
相關文章

聯繫我們

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