Golang切片大小不断增加

时间:2015-08-06 19:24:10

标签: go

我正在学习并正在构建一个小样本控制台应用程序,但遇到了一个我无法理解的问题。

我建造的应用程序模拟公交车正常运营,接送乘客。我遇到的问题是功能(letPassengersOff())似乎增加了乘客数量。

我已经复制了下面的乐趣,但你可以在这里找到应用程序的其余部分:BusRoute

任何人都可以看到我做错了吗?

func letPassengersOff() {
  departing, remaining := []Passenger

  fmt.Println("Number of passengers:", len(b.Passengers))
  for _, value := range b.Passengers {
    if value.ID > 0 {
      if value.EndLocation == b.CurrentStop {
        fmt.Println("Passenger is getting off")
        departing = append(departing, value)
      } else {
        fmt.Println("Passenger is staying on")
        remaining = append(remaining, value)
      }
    }
  }

  fmt.Println("Remaining passengers: ", len(remaining))
  //Setting to nil in the hope that the slice will be cleared
  b.Passengers = nil
  b.Passengers = remaining
  departTheBus(departing)
}    

1 个答案:

答案 0 :(得分:0)

您继续追加到remaining切片。为什么不将切片设置为当前的乘客。我认为“公共汽车”应该已经有乘客吗?

func letPassengersOff(b Bus) {

  remaining := b.Passengers // assume this is a slice
  departing := []Passenger

  fmt.Println("Number of passengers:", len(b.Passengers))
  for i, value := range b.Passengers {
    if value.ID > 0 {
      if value.EndLocation == b.CurrentStop {
        fmt.Println("Passenger is getting off")

        // remove the passenger from remaining and add to departing
        remaining = append(a[:i], a[i+1:]...)
        departing = append(departing, value)

      } else {
        fmt.Println("Passenger is staying on")
        # Do nothing 
      }
    }
  }

  fmt.Println("Remaining passengers: ", len(remaining))
  departTheBus(departing)