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

前端 未结 5 1058
情歌与酒
情歌与酒 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:37

    This is possibly one of the most confusing things in Go. There are basically 3 cases you need to understand:

    The & Operator

    & goes in front of a variable when you want to get that variable's memory address.

    The * Operator

    * goes in front of a variable that holds a memory address and resolves it (it is therefore the counterpart to the & operator). It goes and gets the thing that the pointer was pointing at, e.g. *myString.

    myString := "Hi"
    fmt.Println(*&myString)  // prints "Hi"
    

    or more usefully, something like

    myStructPointer = &myStruct
    // ...
    (*myStructPointer).someAttribute = "New Value"
    

    * in front of a Type

    When * is put in front of a type, e.g. *string, it becomes part of the type declaration, so you can say "this variable holds a pointer to a string". For example:

    var str_pointer *string
    

    So the confusing thing is that the * really gets used for 2 separate (albeit related) things. The star can be an operator or part of a type.

提交回复
热议问题