05 - Functions
📋 Jump to TakeawaysYou've been writing all your code inside main. That works for small programs, but as code grows it gets hard to read and you start repeating yourself. Functions let you name a block of code and call it whenever you need it.
Defining a Function
func greet() {
fmt.Println("Hello!")
}func starts the definition. greet is the name. The parentheses () hold parameters (empty for now). The curly braces hold the code that runs when you call it.
Call it from main:
func main() {
greet() // Hello!
greet() // Hello!
}One definition, called as many times as you want.
Parameters
Functions can accept input:
func greet(name string) {
fmt.Printf("Hello, %s!\n", name)
}
func main() {
greet("Alice") // Hello, Alice!
greet("Bob") // Hello, Bob!
}Multiple parameters:
func add(a int, b int) {
fmt.Println(a + b)
}When consecutive parameters share a type, you can shorten it:
func add(a, b int) {
fmt.Println(a + b)
}Return Values
Functions can send a result back with return:
func add(a, b int) int {
return a + b
}
func main() {
result := add(3, 5)
fmt.Println(result) // 8
}The int after the parentheses is the return type.
Multiple Return Values
Go functions can return more than one value:
func divide(a, b int) (int, int) {
return a / b, a % b
}
func main() {
quotient, remainder := divide(10, 3)
fmt.Println(quotient) // 3
fmt.Println(remainder) // 1
}If you don't need one of the values, use _:
quotient, _ := divide(10, 3)You'll see multiple returns everywhere in Go, especially for error handling (coming in lesson 09).
Functions Change Copies
When you pass a variable to a function, Go makes a copy. The function works with the copy, not the original:
func tryToDouble(n int) {
n = n * 2
fmt.Println("Inside:", n) // Inside: 20
}
func main() {
x := 10
tryToDouble(x)
fmt.Println("Outside:", x) // Outside: 10
}To actually get a new value, return it:
func double(n int) int {
return n * 2
}
func main() {
x := 10
x = double(x)
fmt.Println(x) // 20
}Key Takeaways
func name() { }defines a function- Parameters go inside the parentheses:
func name(x int, y string) - Return types go after the parentheses:
func add(a, b int) int - Go supports multiple return values:
func divide(a, b int) (int, int) - Functions receive copies of their arguments, not the originals
- Return the new value and reassign it to update a variable
- Use
_to ignore a return value you don't need