Functions are very useful when you need to save memory and improve the readability of your code. This is because functions help to organize code in modular sections, enhancing readability.
This guide will teach you how to work with functions in the go programming language. This will help you understand how you can define your own functions in your programs.
The Basics
As mentioned, a function is a piece of code or statements that perform a specific task. Go comes with a collection of pre-defined functions from its standard library.
An example of a popular function is the fmt.Println() function.
Let us understand how we can create custom functions in Go.
Go Define Function
Start by creating a folder called functions and navigate into it.
$ cd functions/
Create a file “functions.go” to store the source code:
To define a function in go, we start with the keyword func. It’s then followed by the name of the function and a pair of parentheses. If a function accepts parameters, you can pass them inside the parentheses. Keep in mind that a function can have no parameters.
Finally, create the function block (what the function does) inside a pair of curly braces.
The general syntax for function definition is as shown:
// function block
}
Let us create a function called greet:
The code above will act like the definition of our function.
Next, we will create a function block that contains the code of what operation the function executes.
fmt.Println("Hi, everyone!")
}
Here, the function prints the string “Hi, everyone!” to the console.
Now that our function is defined and complete, we need to make sure it performs the set task.
Go Call Function
For the function to perform the defined actions, we need to call it. In go, the execution starts at the main function. Hence, we need to call our greet() function inside the main function.
Consider the example code below:
import "fmt"
func main() {
greet()
}
func greet() {
fmt.Println("Hi, everyone!")
}
Now we can run our program as:
Once we run the program, we should see the output of the greet() function as:
Hi, everyone!
NOTE: In go, the main function tells the compiler where the program execution starts. You can only have one main function in a program, and it does not accept any arguments or return any value.
Functions can be more complex than the one we used above. You can use other features of golang such as loops, nested functions, conditional statements, and more.
For example, the function below uses two variables to compare the max value.
import "fmt"
func main() {
max()
}
func max() {
var var1 = 10
var var2 = 100
var maximum = 0;
if var1 > var2 {
maximum = var1
} else {maximum = var2}
fmt.Println(maximum)
}
In the above example, we define a function called max. We then define 3 variables and compare if var1 is greater than var2. If true, we set the maximum value to 1; else, set the maximum value to var2.
Next, we print the value of the maximum variable using the Println method. Once we call the max() function, we should see the largest value as:
100
Go Function Parameters
We mentioned you can create parameters for your functions. Let us look at how we can create functions with parameters.
A parameter refers to a defined unit that acts as an argument that a function can accept.
To define parameters in a function, pass them inside the parentheses during the function definition.
In go, we start by the name of the parameter and its data type. The syntax for defining a function with parameters is as shown:
// function body
}
Let us re-think the max function and see how we can include parameters to make the function more flexible.
We can define two parameters that act as the two values to compare. This allows the user to pass any custom values during the function call.
The resulting function is as shown:
var maximum = 0
if a > b {
maximum = a
} else {
maximum = b
}
fmt.Println(maximum)
}
In this example, the max function takes two values, compares them, and returns the highest. In the main function, we can call the max() function as:
max(100,20)
}
Notice that we can pass custom values than manually hard-coding them inside the function.
HINT: If you have a set of parameters of the same type, you can skip setting the data type for each and simply set it as one type.
For example, since the parameters of the max functions are int, we can define them as:
// function body
}
Go Functions Return Value
If a function can accept a value, it certainly can return one. In golang, we can return a value from a function using the return keyword. When the compiler encounters the return keyword, it exits the functions and returns to the caller function.
You must specify the data type of the return value during function declaration. The syntax is as shown:
// function body
}
Let us modify the max function to return the maximum value instead of printing it using the Println function.
var maximum = 0
if a > b {
maximum = a
} else {
maximum = b
}
return maximum
}
In the example above, you notice we add a return type of int in the function declaration. We then use the return keyword to return the value of the maximum variable.
Since the function returns a value, we can pass that value to other functions as shown in the example below:
// greet()
// max(100,20)
fmt.Println("The max value: ", max(250, 188))
}
The example uses the return value of the max function and passes it to the Println function.
Go also allows you to return multiple values from a function. For example, we can return a string and int from the same function as shown:
// function body
return maximum, "a string return type"
}
In the example above, we return an int and string value.
Conclusion
This guide explored how to work with functions in the go programming language. Keep practicing to become a better programmer.