Sobes.tech
Junior

// What will the following code output and why? package main import "fmt" type Person struct { Name string } func changeName(person *Person) { person = &Person{ Name: "Alice", } } func main() { person := &Person{ Name: "Bob", } fmt.Println(person.Name) changeName(person) fmt.Println(person.Name) }

sobes.tech AI

Answer from AI

The code will output:

Bob
Bob

Explanation:

In the changeName function, the parameter person is a local copy of the pointer to the Person structure. When inside the function person is reassigned to a new address &Person{Name: "Alice"}, this change only affects the local copy of the pointer, not the original pointer passed in main.

Thus, in main, the variable person continues to point to the original object with the name "Bob".

To change the name of the original object, you need to modify the field through the pointer, for example:

func changeName(person *Person) {
    person.Name = "Alice"
}

Then the output will be:

Bob
Alice
// What will the following code output and why… - sobes.tech