Mahdi.Kh
September 21, 2026
Functions help us separate a program's different parts from each other and bring more structure to it.
A function is a self-contained block of code that can take inputs (parameters), perform some operations on them, and then produce a result (output).
To define a function, we use the func keyword:
A function lets us write a part of the program only once and call it whenever we need it.
In the example above, we defined the hello function once and called it 3 times, which causes the text hello world to be printed to the screen three times.
A function can accept one or more values as input (parameters). A function's parameters, or inputs, are variables separated from each other by commas.
In the example above, we defined the introduce function, which prints the values name and age to the screen. We called this function three times with different values.
The return statement ends the function's execution and also returns values. To return values from a function's output, you need to specify the values' types.
In the example above, the last line of the halt function doesn't run, because the return before it exits the function.
In Go, a function can return more than one value. When calling a function, if you don't need one or more of the returned values, you can ignore them using _.
Just like input parameters, output parameters can also be named. If you name the output parameters, calling return ends the function and returns the values of the output parameters.
In the example above, on the last line of the user function, we called return with no arguments at all, which returns the values of name and age as output.
A function that calls itself is called a recursive function. For example, in the code below, we calculate a factorial using a recursive function:
Previous part: The map Data Type | Golang basics
Next part: The struct Data Type | Golang basics