Home > Backend Development > Golang > Introduction to value passing in go language

Introduction to value passing in go language

Release: 2020-06-17 17:27:54
forward
2983 people have browsed it

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]
}
Copy after login

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]
Copy after login

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]
}
Copy after login

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

Introduction to value passing in go language

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!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template