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.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 the main function, a pointer to a Person struct with the name "Bob" is created.
  • The first print statement outputs person.Name — "Bob".
  • The changeName function takes a pointer to a Person and changes the Name field to "Alice".
  • After calling changeName, the value of the field is changed, so the second output shows "Alice".

In Go, passing a pointer to a function that modifies a struct reflects on the original object.

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