Anonymous Functions (aka Closures)
·
234 words
·
2 minutes read
Here is a basic example of how an anonymous function, or lambda function, can be used with Go. We’re just printing a statement to screen, but it can be used for various things - one of which can be just to segment code which will only need to get run once and doesn’t need to be referenced.
It also has the use case of encapsulating the variables used within itself, so only from within are you able to access a variable from within. Once the function has finished the variables can then be garbage collected. To pass data into the function we have to add it to the execution parenthesis at the end.
|
|
This technique is especially useful in Go, because once you have this structure, you can turn it into a goroutine by simple adding the word go
before your func
.
This is also possible:
|
|
This is not possible:
|
|