简体   繁体   English

Goroutine填充结构实例切片

[英]Goroutine to populate struct instance slice

This is my first day using Go and I had a question about goroutines and appending to an instance's slice. 这是我使用Go的第一天,我有一个关于goroutine并附加到实例切片的问题。

The idea is that each Truck would have a Cargo of length 1 containing an Item with name "Groceries". 这个想法是,每辆卡车将有一个长度为1的货物,其中包含一个名为“杂货”的商品。 I almost have it, but for some reason it's losing the properties of the truck, and it seems to be terminating prematurely. 我几乎拥有它,但由于某种原因,它正在失去卡车的性能,并且似乎过早终止。

https://play.golang.org/p/f0uIy5qg8d https://play.golang.org/p/f0uIy5qg8d

 package main import "fmt" import "time" type Item struct { name string } type Truck struct{ Cargo []Item name string } func UnloadTrucks(ch chan *Truck){ t := <- ch fmt.Printf("%s has %d items in cargo: %s\\n", t.name, len(t.Cargo), t.Cargo[0].name) time.Sleep(1 * time.Second) return } func main() { trucks := make([]Truck, 2) ch := make(chan *Truck) for i, t := range trucks{ t.name = fmt.Sprintf("Truck %d", i + 1) fmt.Printf("Building %s\\n", t.name) } for _, t := range trucks { go func(tr *Truck){ itm := Item {} itm.name = "Groceries" fmt.Printf("Loading %s", tr.name) tr.Cargo = append(tr.Cargo, itm) ch <- tr }(&t) } UnloadTrucks(ch) } 

Your issue is not that the truck's properties are "lost", but they're never set in the first place. 您的问题不是卡车的属性“丢失”,而是永远不会将其设置为第一位。 This loop is your problem: 这个循环是您的问题:

for i, t := range trucks {
    t.name = fmt.Sprintf("Truck %d", i + 1)
    fmt.Printf("Building %s\n", t.name)
}

Within this loop, t is a copy of the Truck object in the trucks slice. 在此循环内, ttrucks切片中卡车对象的副本 Any modification on this object will not affect the original truck. 对此对象进行的任何修改都不会影响原始卡车。 Instead, you can reference the original Truck object by using the index variable i to directly access the object in the trucks slice: 相反,您可以通过使用索引变量i直接访问trucks切片中的对象来引用原始的卡车对象:

for i, _ := range trucks {
    trucks[i].name = fmt.Sprintf("Truck %d", i + 1)
    fmt.Printf("Building %s\n", trucks[i].name)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM