Goroutine用于填充结构实例切片。

huangapple go评论86阅读模式
英文:

Goroutine to populate struct instance slice

问题

这是我第一天使用Go语言,我对goroutines和向实例的切片追加内容有一个问题。

想法是每个卡车都有一个长度为1的货物,其中包含一个名为“Groceries”的物品。我几乎做到了,但由于某种原因它丢失了卡车的属性,并且似乎提前终止了。

以下是代码:

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)
}

你可以在这里运行代码并查看结果:https://play.golang.org/p/f0uIy5qg8d

英文:

This is my first day using Go and I had a question about goroutines and appending to an instance's slice.

The idea is that each Truck would have a Cargo of length 1 containing an Item with name "Groceries". 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

<!-- begin snippet: js hide: false -->

<!-- language: lang-html -->

package main

import &quot;fmt&quot;
import &quot;time&quot;

type Item struct {
   name string
}

type Truck struct{
   Cargo []Item
   name  string
}

func UnloadTrucks(ch chan *Truck){
    t := &lt;- ch

    fmt.Printf(&quot;%s has %d items in cargo: %s\n&quot;, 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(&quot;Truck %d&quot;, i + 1)

	 fmt.Printf(&quot;Building %s\n&quot;, t.name)
     }



     for _, t := range trucks {
            go func(tr *Truck){
		  itm := Item {}
                  itm.name = &quot;Groceries&quot;


     	          fmt.Printf(&quot;Loading %s&quot;, tr.name)
                  tr.Cargo = append(tr.Cargo, itm)
                  ch &lt;- tr

            }(&amp;t)
     }

     UnloadTrucks(ch)
}

<!-- end snippet -->

答案1

得分: 1

你的问题不是卡车的属性“丢失”,而是它们从一开始就没有被设置。这个循环是你的问题所在:

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

在这个循环中,ttrucks 切片中卡车对象的一个副本。对该对象的任何修改都不会影响原始卡车。相反,你可以使用索引变量 i 直接访问 trucks 切片中的对象来引用原始卡车对象:

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

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(&quot;Truck %d&quot;, i + 1)
    fmt.Printf(&quot;Building %s\n&quot;, t.name)
}

Within this loop, t is a copy of the Truck object in the trucks slice. 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:

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

huangapple
  • 本文由 发表于 2015年12月30日 01:55:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/34516342.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定