Go語言里的傳值與傳引用大致與C語言中一致,但有2個特例,map和channel默認傳引用,也就是說可以直接修改傳入的參數,其他的情況如果不用指針的話,傳入的都是參數的副本,在函數中修改不會改變調用者中的變量值。簡單的做了一個例子:
package main
import "fmt"
func main() {
fmt.Println("Hello from Go start")
var sVal string
var sRef string
var dVal []byte
var dRef []byte
var mVal map[string]string = make(map[string]string, 1)
var mRef map[string]string = make(map[string]string, 1)
sRet, dRet := paramsTest(sVal, &sRef, dVal, &dRef, mVal, &mRef)
fmt.Printf("sVal:%s\n", sVal)
fmt.Printf("sRef:%s\n", sRef)
fmt.Printf("dVal:%s\n", string(dVal))
fmt.Printf("dRef:%s\n", string(dRef))
fmt.Printf("sRet:%s\n", string(sRet))
fmt.Printf("dRet:%s\n", string(dRet))
var k, v string
for k, v = range mVal {
fmt.Printf("mVal[%s]:%s\n", k, v)
}
for k, v = range mRef {
fmt.Printf("mRef[%s]:%s\n", k, v)
}
fmt.Println("Hello from Go end")
}
func paramsTest(sVal string, sRef *string, dVal []byte, dRef *[]byte, mVal map[string]string, mRef *map[string]string) (sRet string, dRet []byte) {
sVal = "sVal"
*sRef = "sRef"
dVal = []byte("dVal")
*dRef = []byte("dRef")
sRet = "sRet"
dRet = []byte("dRet")
mVal["mVal"] = "mVal"
(*mRef)["mRef"] = "mRef"
return sRet, dRet
}
結果輸出:
Hello from Go start sVal: sRef:sRef dVal: dRef:dRef sRet:sRet dRet:dRet mVal[mVal]:mVal mRef[mRef]:mRef Hello from Go end
驗證了官方的說法。可見萬變不離其宗,編程無他,唯手熟爾。
學習知識的法則: 學習 + 實踐 + 思考
