Callbacks
Now that we know how to use WaitGroups, we can also introduce the concept of callbacks. If you have ever worked with languages like JavaScript that use them extensively, this section will be familiar to you. A callback is an anonymous function that will be executed within the context of a different function.
For example, we want to write a function to convert a string to uppercase, as well as making it asynchronous. How do we write this function so that we can work with callbacks? There's a little trick-we can have have a function that takes a string and returns a string:
func toUpperSync(word string) string { //Code will go here }
So take the returning type of this function (a string) and put it as the second parameter in an anonymous function, as shown here:
func toUpperSync(word string, f func(string)) { //Code will go here }
Now, the toUpperSync
function returns nothing, but also takes a function that, by coincidence, also takes a string...