我想遍历结构数组并修改每个项目。但是,以下代码中的结构尽管分配了新值,但仍保持相同。该代码可以正常编译。由于该结构是自引用的,因此我使用了指针。我不确定这是否会使以后的重新分配变得复杂。
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
}
}
}