這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
1.對於普通函數,接收者為實值型別時,不能將指標類型的資料直接傳遞,反之亦然。
2.對於方法(如struct的方法),接收者為實值型別時,可以直接用指標類型的變數調用方法,反過來同樣也可以。
以下為簡單樣本:
package structTest//普通函數與方法的區別(在接收者分別為實值型別和指標類型的時候)//Date:2014-4-3 10:00:07import ("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 := 2fmt.Println("valueIntTest:", valueIntTest(a))//函數的參數為實值型別,則不能直接將指標作為參數傳遞//fmt.Println("valueIntTest:", valueIntTest(&a))//compile error: cannot use &a (type *int) as type int in function argumentb := 5fmt.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 intname 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()//與普通函數不同,接收者為指標類型和實值型別的方法,指標類型和實值型別的變數均可相互調用}