I'm learning go and am building a little sample console app but have run into a problem that I can't get my head around.
The app I'm building simulates a bus going about it's normal business, picking up and dropping passengers off. The issue I'm having is that a function (letPassengersOff()) seems to be increasing the number of passengers.
I've copied the fun below but you can find the rest of the application here: BusRoute
Can anyone see what I'm doing wrong?
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)
}
You keep appending to the remaining
slice. Why not set the slice to the current Passengers. I assume that a "bus" should already have passengers on it?
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)