0

How come Go can be initialized using both &Person and Person?

package main

import "fmt"

type Person struct {
    name string
}

func (p Person) Who() string {
    return "Person: " + p.name
}

func main() {
    var p1 = &Person{"Adam"}
    fmt.Println(p1.Who()) // Adam
    var p2 = Person{"Ben"}
    fmt.Println(p2.Who()) // Ben
}
2
  • 2
    Could you be more specific with your question? What do you see as the issue in your sample code? Commented Jun 23, 2021 at 1:33
  • Person{} creates a Person and & takes the address of that Person variable. It's not the same. Please take the Tour of Go to learn the syntax and how to work with pointers. Commented Jun 23, 2021 at 4:20

1 Answer 1

5

p2 := Person{"Ben"} initializes a Person struct by assigning "Ben" to name, and assigned that to p2. p2 is of a value type Person.

p1 := &Person{"Adam"} initializes a Person struct by assigning "Adam" to name, and then assigns the address of that struct to p1. p1 is of a pointer type *Person.

Who() is a method defined for a receiver of value type Person, which means, the functionality always receives a copy of the receiving instance. This is an important factor when it comes to mutability. This also works with pointer handles, such as in your example with p2, but the receiver will continue to be a local copy of the instance, unless you change the receiver definition to (p *Person), which will provide a local copy of the pointer reference.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.