Home > Article > Backend Development > Introduction to value passing in go language
Parameters in Go language can only be passed by value
Value passing is a copying process
Go: Value passing
func bbb(list [4]int){ for i,_ := range list{ list[i] = 0 } } func main(){ list := [4]int{1,2,3,4} bbb(list) fmt.Println(list ) //[1 2 3 4] }
Javascript: Reference passing
let list = [1,2,3,4] function bbb(list){ list.forEach((item,index)=>{ list[index] = 0 }) } bbb(list) console.log(list) //[0,0,0,0]
But Go language can realize the function of reference passing through pointers
func bbb(p2 *[4]int){ //接受一个[4]int的指针 for i,_ := range p2{ p2[i] = 0 } } func main(){ list := [4]int{1,2,3,4} p := &list bbb(p) //传递指针 fmt.Println(list ) //[0 0 0 0] }
Since it is said that parameter passing in go language can only be passed by value, So here is actually a copy of the pointer address, and both addresses point to the address of the variable list of the main function, so the value of the list changes
For more related knowledge, please pay attention to go language tutorial column
The above is the detailed content of Introduction to value passing in go language. For more information, please follow other related articles on the PHP Chinese website!