A function is a container for a few lines of code that perform a specific task.
Functions allow us to organize code by breaking it into smaller, more manageable chunks that each do one clear thing.
Here's how a function definition looks in Go:
func functionName() {
// function body
}
There are two main components of a function:
1. The function header:
functells Go that we are defining a function.functionNameis the function's name.- Parentheses (
()) appear after the name. We'll use them for parameters in later lessons. - Curly braces (
{}) contain the function body.
2. The function body:
This is the code that Go executes whenever the function is called.
Here's an example:
func sayHello() {
fmt.Println("Hello World")
}
Calling a function
A function declaration alone does not run the code inside the function body. It only declares that the function exists.
The code inside a function runs only when the function is called.
You can call or invoke a function by typing its name followed by parentheses:
func sayHello() {
fmt.Println("Hello World")
}
func mainFunction() {
sayHello() // Output: Hello World
}
All of the code inside the function body is executed every time the function is called.
Capitalization = exported:
In Go, a name that starts with a Capital letter (Foo) is exported — other packages can use it. A name that starts with a lowercase letter (foo) is private to its own package. This rule applies to functions, types, and struct fields alike.
func SayHello() {} // exported (capital S) — usable from other packages
func sayHello() {} // private to this package (lowercase s)
That's why you'll see fmt.Println with a capital P in the coding tutorials: it's exported from the fmt package.
Assignment
Follow the Coding Tutorial and let's write some functions.
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. PRO is unlimited.
