您的问题是您的结构具有非指针切片。在所有结构中,像这样将切片定义为指针切片
Rooms []*Room
您还需要定义函数以获取指针值,如下所示
func(room *Room) {}
详细说明。Go是按值传递。每当您从原始切片之一中拉出某些东西并将其传递给您的功能之一时,它都会得到一个副本。使用指针会修改切片中的实际值。
请参阅此示例。https://play.golang.org/p/ZThHrP0pds
package mainimport ( "fmt")type Thing struct { Name string}func main() { things := []Thing{} thing := Thing{"thing1"} // add to slice // note that this is a function call things = append(things, thing) // attempt to change thing.Name = "thing2" fmt.Println(things[0].Name) // prints thing1 fmt.Println(thing.Name) // prints thing2 fmt.Println("------") // try again thing3 := things[0] thing3.Name = "thing3" // fail again fmt.Println(things[0].Name) // prints thing1 fmt.Println(thing3.Name) // prints thing3 fmt.Println("------") // do this instead betterThings := []*Thing{} // slice of pointers betterThing := &Thing{"thing2"} // betterThing is of type *Thing // add to slice betterThings = append(betterThings, betterThing) // successfully change betterThing.Name = "thing2" fmt.Println(betterThings[0].Name) // prints thing2 fmt.Println(betterThing.Name) // prints thing2}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)