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) // Bob changeName(person) fmt.Println(person.Name) // Bob }

sobes.tech AI

Answer from AI

The code will output:

Bob
Alice

Explanation:

  • In main, a pointer person to a Person struct with the name "Bob" is created.
  • The first fmt.Println(person.Name) prints "Bob".
  • The changeName function takes a pointer to Person and assigns a new struct with the name "Alice" to that pointer.
  • This changes the content at the address person points to.
  • Therefore, after calling changeName(person), the value of person.Name becomes "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".

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