Go Functions Tutorial
In this tutorial, we are going to be looking at Go’s functions and hopefully, by the end of this tutorial, you will have a firm grasp as to what they are and how you can use them in your own projects.
So, to make this interesting, we are going to be building a program a really simple command-line interface tool that we can extend to our hearts content.
Function Declaration
The first thing we’ll need to figure out is, how do you declare a function within a go program? Now, if you are en experienced programmer then this should be nothing new to you. We start off by using the func
keyword and then specifying the name of the our function.
Once we’ve specified the name we’ll want to specify our parameter list, essentially what parameters we wish to pass into this function. If we don’t wish to pass any parameters into the function then we just use empty parenthesis.
It’s after we define our parameter list that things start to deviate from the norm. Just after the parameter list, we define the result list that is returned whenever someone calls our function.
|
|
So how does this look in a real go program?
|
|
And the full program would look like this:
|
|
It’s quite often in Go programs that you’ll see two results being returned from a function call. This is typically the result as the first result and any potential errors as the second result. This practice can be very useful and allows go programmers to decide what to do with an error within the original function block that called out to a second function:
|
|
Anonymous Functions
If you come from a Python background, you may be comfortable with anonymous functions, however, if you aren’t then fear not!
Anonymous functions are very similar to regular functions except they lack a named identifier. These functions can be defined within named functions and can have access to any variables within it’s enclosing function like so:
|
|
Conclusion
So, in this article we managed to cover quite a fair bit on functions within the go programming language. Hopefully, you found this useful! If you require any further help or assistance then please feel free to let me know in the comments section below!