golang物件導向

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

golang中並沒有明確的物件導向的說法,實在要扯上的話,可以將struct比作其它語言中的class。

類的聲明:

//聲明一個類type People struct {    Name    string    Sex     int32    Address string}

這樣就聲明了一個類,其中沒有public、protected、private的的聲明。golang用另外一種做法來實現屬性的存取權限:屬性的開頭字母是大寫的則在其它包中可以被訪問,否則只能在本包中訪問。類的聲明和方法亦是如此。

類方法聲明:

//聲明一個類的方法func (people People) Publish() {    fmt.Println("method :Publish")}func (people *People) Show(name string) {    fmt.Println(name)}

和其它語言不一樣,golang聲明方法和普通方法一致,只是在func後增加了poem *Poem這樣的聲明。加*和沒有加*的區別在於一個是傳遞指標對象,一個是傳遞值對象。

執行個體化對象:

//執行個體化People類對象    p := &People{}    p.Name = "Name1"    fmt.Println("p Name:", p.Name)    p2 := &People{Name: "Name2"}    fmt.Println("p2 Name:", p2.Name)    p3 := new(People)    p3.Name = "Name3"    fmt.Println("p3 Name:", p3.Name)    p4 := People{}    p4.Name = "Name4"    fmt.Println("p4 Name:", p4.Name)    p5 := People{Name: "Name5"}    fmt.Println("p5 Name:", p5.Name)    p6 := NewPeople("張三")    fmt.Println("p6:Name-", p6.Name)

執行個體化的時候可以初始化屬性值,如果沒有指明則預設為系統預設值

加&符號和new的是指標對象,沒有的則是值對象,這點和php、java不一致,在傳遞對象的時候要根據實際情況來決定是要傳遞指標還是值。

小技巧提示:當對象比較小的時候傳遞指標並不划算。

建構函式:

golang並沒有建構函式一說。如果一定要在初始化對象的時候進行一些工作的話,可以自行封裝產生執行個體的方法。

 func New類名(param string, p ...interface{}) (參數 *類名)
//建構函式func NewPeople(name string) (people *People) {    people = &People{} //初始化    people.Name = name    people.Show(name)    return}

建構函式的調用

p6 := NewPeople("張三")    fmt.Println("p6:Name-", p6.Name)

 

繼承(組合):

//類的繼承也可以稱為類的組合type ChinaPeople struct {    People    Title string    Name  string}

 

ChinaPeople 屬性中聲明了Name,表示組合了People的屬性和方法。可以像如下方式調用(如果其中屬性有衝突,則以外圍的為主。):

chinaP := &ChinaPeople{}    chinaP.Name = "China"    fmt.Println(chinaP)    fmt.Println("ChinaPeople Name:", chinaP.Name, " of value")    chinaP.People.Name = "People-Name"    fmt.Println(chinaP)    fmt.Println("People Name", chinaP.People.Name, " of value")

輸出結果:

方法重載:

//方法重載func (people *People) Receive(v ...interface{}) {    fmt.Println(v)}

重載調用:

    fmt.Println("方法的重載:")    p7 := &People{}    p7.Receive("Receive", 890)    p7.Receive("Receive", 890, "abcd")


執行結果:

 

聯繫我們

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