- Learning Functional Programming in Go
- Lex Sheehan
- 268字
- 2021-07-02 23:13:44
Finishing up the GenerateCars function
At the end of our GenerateCars function, we execute another anonymous Goroutine. The purpose of this Goroutine is to wait for all the previously launched Goroutine generators to complete. We use waitGroup.Wait to know when the last generator was completed. Then, it's safe to close carChannel:
go func() {
waitGroup.Wait()
println("close channel")
close(carChannel)
}()
for thisCar := range carChannel {
generatedCars = append(generatedCars, thisCar.Car)
}
return generatedCars
}
The carChannel will block until it receives a new car; this is a result of calling GetThisCar(carIndex). Recall that WaitGroup.Add(numCarsToGenerate) told WaitGroup how many cars we'd process. The waitGroup.Done() function counts that number down to 0, at which time waitGroup.Wait() is executed and carChannel is closed.
We wait until all our Goroutines have fetched data from the RESTful HTTP server before returning the generatedCars collection. This is a common pattern in FP: we eliminate as much state change in our data transformation operation as possible. We wait until all of our data collection processing has completed and then we finally return the final result.
Our FP work is much like that of an electrician. Electricians turn off the power, hook up all the wires in the building, and when everything is in place, they flip the power switch and all the lights come on. Data is power. Don't let your data fly until the last possible moment.
In the main.go file, add the following code:
PrintCars("GenerateCars(1, 3)",
cars.GenerateCars(1, 3))
The following is its output:
GenerateCars(1, 3)
-----------------------
car: Honda CR-V
car: Honda Accord ES2
car: Lexus IS250