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) // Bob changeName(person) fmt.Println(person.Name) // Bob }
sobes.tech AI
Answer from AI
The code will output:
Bob
Alice
Explanation:
- In
main, a pointerpersonto aPersonstruct with the name "Bob" is created. - The first
fmt.Println(person.Name)prints "Bob". - The
changeNamefunction takes a pointer toPersonand assigns a new struct with the name "Alice" to that pointer. - This changes the content at the address
personpoints to. - Therefore, after calling
changeName(person), the value ofperson.Namebecomes "Alice".
In your example comments, it is stated that the second output will be "Bob", but this is incorrect. Since the function changes the value by pointer, the name will change to "Alice".