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 ", sVal) fmt.Printf("sRef:%s ", sRef) fmt.Printf("dVal:%s ", string(dVal)) fmt.Printf("dRef:%s ", string(dRef)) fmt.Printf("sRet:%s ", string(sRet)) fmt.Printf("dRet:%s ", string(dRet)) var k, v string for k, v = range mVal { fmt.Printf("mVal[%s]:%s ", k, v) } for k, v = range mRef { fmt.Printf("mRef[%s]:%s ", 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
验证了官方的说法。可见万变不离其宗,编程无他,唯手熟尔。
学习知识的法则: 学习 + 实践 + 思考