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

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

王林
Release: 2024-02-05 21:30:04
forward
1077 people have browsed it

(*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)
}
Copy after login

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!

source:stackoverflow.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