This question already has an answer here:
I would like to iterate through an array of structs and modify each item. However, the structs in the following code remain the same despite being assigned new values. The code compiles fine. Since the struct is self referential, I'm using pointers. I'm not sure if that complicates the later reassignments.
package main
import "fmt"
type Actor struct {
name string
i int
bff *Actor
}
func main() {
var bob Actor
bob.name = "Bob"
bob.i = 10
var sara Actor
sara.name = "Sarah"
sara.i = 20
var john Actor
john.name = "John"
john.i = 30
bob.bff = &sara
sara.bff = &john
john.bff = &bob
actors := []Actor{bob, sara, john}
for turn := 1; turn <= 3; turn++ {
fmt.Println("----------Turn", turn, "----------")
for _, actor := range actors {
fmt.Println(actor.name, ": i =", actor.i, " bff=", actor.bff.name)
if actor.bff == &john {
actor.bff = &sara
} else if actor.bff == &sara {
actor.bff = &bob
} else if actor.bff == &bob {
actor.bff = &john
}
actor.i = actor.i + turn
}
}
}
</div>