Go Functions
What is a Function?
A function is similar to a variable, but instead of storing numbers or text, it stores lines of code for Go to run. Functions in Go and other languages can have inputs, or parameters, as we will learn in this tutorial.
Why use Functions?
Let's say that you wanted to write some code to make buttons on a website an you have to write 5 lines of code to make each button. If you only needed to make 10 buttons. That would be 500 lines of code. Not too bad. But once you need more and more buttons, the number of lines of code keep growing and growing. If you want to edit all your buttons, you would now have to go through hundreds of lines of code. Instead of getting into this mess, you could make a function to make a button. Now, instead of writing 5 lines of code, you only need to write a single line of code. Plus, changing the button is as simple as changing the code inside the function.
Making Functions in Go
Try running the following Go code:
package main
import "fmt"
func hello(name string) {
fmt.Println("Hello " + name)
}
func main() {
var name = "Coder Monkey"
hello(name)
}
Code Breakdown
Now that you have written the code, we will now break it down and see how it works.
Well, the only NEW code we wrote was:
func hello(name string) {
fmt.Println("Hello " + name)
}
On the first line, we have
func hello(name string) {
This is called declaring a function, much like a variable. We type func
to tell Go that our code is a function and we name it hello
. Then, we write name string
in the brackets. Basically, this is an argument, also known as a parameter. This is used to pass information and variables to our function. We can even pass in other functions! Writing string
means that the name
argument MUST be a string Data Type. After, we write the curly bracket ({
) to tell Go that the next lines of code, before the closing curly bracket (}
), to be the code that runs when we call our hello
function.
On the next line, we have fmt.Println("Hello " + name)
. We already know that fmt.Println
prints text, but what is the +
doing between "Hello "
and the variable name
? Well, in programming, we call this string concatenation, or simply just combinging two strings together. In this case, we put "Hello "
before the variable name
so the final result will be Hello name
. Then, the function will print that out.
Finally, we close of with the closing curly bracket (}
) which tells Go to end our function.
Running A Function
To run a function in Go, we just write functionname()
and any parameters/arguments the function takes in the brackets. For example, to run our hello
function, we can write hello("Monkey Coder")
and the program will output Hello Monkey Coder