A function is a collection of code that you can call from your program. You can pass values to a function and they can return a result. They also help keep your programs organised, a function can be called multiple times and be reused in other programs.
Functions also help with security and maintenance, any improvements to a function benefits your program anywhere it is called.
This simple function prints a message.
func hello() {
fmt.Println("Hello World!")
}
We can call the above function as follows:
hello()
The following function takes two values and returns and the area of the shape as an integer.
func myarea(width int, height int) int {
return width * height
}
We can pass the function to a variable or use it directly:
fmt.Println("Area:", myarea(5, 5))
A feature of Go is that a function can return more that one value, often this is used to return a boolean (true/false) of whether the function was successful and a result.
We can expand the above area function to return two integers, an area and perimeter:
func myshape(width int, height int) (int, int) {
return (width * height), (width + height) * 2
}
We can use the above function as follows:
area, perimeter := myshape(5, 5)
fmt.Println("Area:", area, " Perimeter:", perimeter)
The Go compiling guide explains the folder set up for a Go program, once that is done:
package main import ( "fmt" ) // Returning no value func hello() { fmt.Println("Hello World!") } // Returning one value func myarea(width int, height int) int { return width * height } // Returning two values func myshape(width int, height int) (int, int) { return (width * height), (width + height) * 2 } func main() { hello() fmt.Println("Area:", myarea(5, 5)) // Putting the function results into two variables area, perimeter := myshape(5, 5) fmt.Println("Area:", area, " Perimeter:", perimeter) }
Updated (06/08/2026)