Functions
Prerequisites: Maps
Syntax
func name(param1 type1, param2 type2) returnType {
return value
}
func add(a, b int) int { // same-type params can share a type
return a + b
}
func greet(name string) { // no return value
fmt.Println("Hello,", name)
}
- Arguments are passed by value — the function receives a copy.
- A variadic parameter (
nums ...int) accepts any number of arguments and arrives inside the function as a slice. - Functions are values: you can store them in variables and write anonymous functions inline.
- Go has no default parameter values and no function overloading — each function name in a package is unique.
Example
package main
import "fmt"
func add(a, b int) int {
return a + b
}
func sum(nums ...int) int {
total := 0
for _, n := range nums {
total += n
}
return total
}
func resetToZero(n int) {
n = 0 // only changes the local copy
}
func main() {
fmt.Println(add(2, 3))
fmt.Println(sum(1, 2, 3, 4))
values := []int{10, 20, 30}
fmt.Println(sum(values...)) // spread a slice into a variadic call
x := 5
resetToZero(x)
fmt.Println(x)
square := func(n int) int {
return n * n
}
fmt.Println(square(6))
}
Expected output
5
10
60
5
36
x is still 5 because resetToZero received a copy. To let a
function change a caller's variable you pass a pointer —
covered in the Pointers lesson.
Common mistakes
- Declaring a return type and forgetting a
returnon some path —missing returnis a compile error. - Expecting a function to modify an argument it received by value.
- Naming a function
max,min,len, orappend. It's legal, but it hides the built-in with the same name inside that scope.
Practice
Write a function isEven(n int) bool and a variadic function
average(nums ...float64) float64. Print isEven(7) and
average(2, 4, 9).
Show solution
package main
import "fmt"
func isEven(n int) bool {
return n%2 == 0
}
func average(nums ...float64) float64 {
if len(nums) == 0 {
return 0
}
total := 0.0
for _, n := range nums {
total += n
}
return total / float64(len(nums))
}
func main() {
fmt.Println(isEven(7)) // false
fmt.Println(average(2, 4, 9)) // 5
}