Methods as Routines
So far, you've only seen functions used as Goroutines, but methods are simple functions with a receiver; hence, they can be used asynchronously too. This can be useful if you want to share some properties of your struct, such as for your counter in an HTTP server.
With this technique, you can encapsulate the channels you use across several routines belonging to the same instance of a struct without having to pass these channels everywhere.
Here is a simple example of how to do that:
type MyStruct struct {} func (m MyStruct) doIt() . . . . . . ms := MyStruct{} go ms.doIt()
But let's see how to apply this in an exercise.
Exercise 16.10: A Structured Work
In this exercise, we will calculate a sum using several workers. A worker is essentially a function, and we will be organizing these workers into a single struct.
- Create your folder and
main
file. In it, add the required imports and define aWorker
struct with two channels –...