What is the meaning of '*' and '&'?

前端 未结 5 1135
情歌与酒
情歌与酒 2021-01-30 09:07

I am doing the http://tour.golang.org/. Could anyone explain me lines 1,3,5 and 7 this function especially what \'*\' and \'&\' do? I mean by mentioning the

5条回答
  •  逝去的感伤
    2021-01-30 09:29

    This is by far the easiest way to understand all the three cases as explained in the @Everett answer

    func zero(x int) {
      x = 0
    }
    func main() {
      x := 5
      zero(x)
      fmt.Println(x) // x is still 5
    }
    

    If you need a variable to be changed inside a function then pass the memory address as a parmeter and use the pointer of this memory address to change the variable permanently.

    Observe the use of * in front of int in the example. Here it just represents the variable that is passed as a parameter is the address of type int.

    func zero(xPtr *int) {
      *xPtr = 0
    }
    func main() {
      x := 5
      zero(&x)
      fmt.Println(x) // x is 0
    }
    

提交回复
热议问题