1. 程式人生 > >Go語言學習(十二)面向物件程式設計-結構體

Go語言學習(十二)面向物件程式設計-結構體

1.結構體的初始化方式

例如自定義一個結構體

package main

import(
    "fmt"
)
type Rect struct{  //type和struct為關鍵字
    x,y float64  //結構體成員
    widh,height float64
}

func (r *Rect) Area() float64{
    return r.width * r.height
}

func main(){
    //初始結構體的幾種方式:
    rect1 := new(Rect)
    rect2 := &Rect{}
    rect3 := &Rect{0
,0,100,200} rect4 := &Rect{widh:100,height:200} }

在Go語言中,未進行顯式初始化的變數都會被初始化為該型別的”零值”,
例如bool型別的零值為false,int型別的零值為0,string 型別的零值為空字串。

在Go語言中沒有建構函式的概念,物件的建立通常交由一個全域性的建立函式來完成,以
NewXXX來命名,表示“建構函式”:

func newRect(x,y,widh,height float64) *Rect{
    return &Rect{x,y,widh,height}
}

這一切非常自然,開發者也不需要分析在使用了 new 之後到底背後發生了多少事情。在Go
語言中,一切要發生的事情都直接可以看到。

2.巢狀結構體

package main
import(
    "fmt"
)
func main(){
    t := space{plane{line{3}, 5}, 7}
    fmt.Println(t.x, t.y, t.z)  //3 5 7
}

type line struct {
    x int
}
type plane struct {
    line
    y int
}
type space struct {
    plane
    z int
}

3.結構體的特點:

1)結構體可以儲存不同的型別
2)在記憶體中佔據連續的記憶體空間
3)結構體每一個項所佔用的記憶體大小不一定相同
4)結構體支援組合,即結構體可以保護結構體
5)通過操作結構體的項名t.x、t.y、t.z來獲取欄位值
6)判斷兩個結構體是否相同,需要看結構體的型別是否相同,
然後看項的順序、項的名稱、項的型別等等.
7)結構體的成員初始化是通過操作欄位賦值來完成