Home >Backend Development >Golang >What is the difference between (*variable) and *&variable?

What is the difference between (*variable) and *&variable?

王林
王林forward
2024-02-05 21:30:041086browse

(*variable) 和 *&variable 有什么区别?

Question content

I am using exercism.com to learn go and reading the documentation and articles recommended in the syllabus.

Now I'm in the structure and find the next code

package main

import "fmt"

type Employee struct {
  firstName, lastName string
  salary              int
  fullTime            bool
}

func main() {
  employee := &Employee{
    firstName: "Walddys",
    lastName:  "Dorrejo",
    salary:    1200,
    fullTime:  true,
  }
  fmt.Println("firstName", (*employee).firstName)
}

But by mistake, I entered fmt.println("firstname", *&employee.firstname), which gave me the same result as I had used before in the code block.

My question is, is there a difference or the same in using this pointer?


Correct answer


##&x generates a pointer to x while *p dereferences Pointerp. Therefore * and & effectively cancel each other out, e.g. the two statements v := *&x and v := x are identical.

This means

*&employee.firstName is the same as employee.firstName.

Where

employee is a pointer to the structure, and firstName is a field of the structure, then the expression employee.firstName is actually ## Abbreviation for #(*employee).firstName. This means

*&employee.firstName

is also the same as (*employee).firstName. Please note that you should always prefer using shorthand notation.

The above is the detailed content of What is the difference between (*variable) and *&variable?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete