Go語言中普通函數與方法的區別分析_Golang

來源:互聯網
上載者:User

本文執行個體分析了Go語言中普通函數與方法的區別。分享給大家供大家參考。具體分析如下:

1.對於普通函數,接收者為實值型別時,不能將指標類型的資料直接傳遞,反之亦然。

2.對於方法(如struct的方法),接收者為實值型別時,可以直接用指標類型的變數調用方法,反過來同樣也可以。

以下為簡單樣本:

複製代碼 代碼如下:
package structTest 
 
//普通函數與方法的區別(在接收者分別為實值型別和指標類型的時候) 
//Date:2014-4-3 10:00:07 
 
import ( 
    "fmt" 
) 
 
func StructTest06Base() { 
    structTest0601() 
    structTest0602() 
} 
 
//1.普通函數 
//接收實值型別參數的函數 
func valueIntTest(a int) int { 
    return a + 10 
} 
 
//接收指標型別參數的函數 
func pointerIntTest(a *int) int { 
    return *a + 10 
} 
 
func structTest0601() { 
    a := 2 
    fmt.Println("valueIntTest:", valueIntTest(a)) 
    //函數的參數為實值型別,則不能直接將指標作為參數傳遞 
    //fmt.Println("valueIntTest:", valueIntTest(&a)) 
    //compile error: cannot use &a (type *int) as type int in function argument 
 
    b := 5 
    fmt.Println("pointerIntTest:", pointerIntTest(&b)) 
    //同樣,當函數的參數為指標類型時,也不能直接將實值型別作為參數傳遞 
    //fmt.Println("pointerIntTest:", pointerIntTest(b)) 
    //compile error:cannot use b (type int) as type *int in function argument 
} 
 
//2.方法 
type PersonD struct { 
    id   int 
    name string 
} 
 
//接收者為實值型別 
func (p PersonD) valueShowName() { 
    fmt.Println(p.name) 
} 
 
//接收者為指標類型 
func (p *PersonD) pointShowName() { 
    fmt.Println(p.name) 
} 
 
func structTest0602() { 
    //實值型別調用方法 
    personValue := PersonD{101, "Will Smith"} 
    personValue.valueShowName() 
    personValue.pointShowName() 
 
    //指標類型調用方法 
    personPointer := &PersonD{102, "Paul Tony"} 
    personPointer.valueShowName() 
    personPointer.pointShowName() 
 
    //與普通函數不同,接收者為指標類型和實值型別的方法,指標類型和實值型別的變數均可相互調用 
}

希望本文所述對大家的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.