Functions
Scope: declaring functions, multiple return values, named results, and the exported/unexported naming rule. All examples were compiled and run.
The basics
func add(a int, b int) int {
return a + b
}
Or the shorthand when parameters share a type:
func add(a, b int) int {
return a + b
}
Types come after the name (a int, not int a) — unusual if
you're coming from C, normal after a day.
Multiple return values
Go functions can return more than one value. This is central to how Go handles errors (see Error Handling):
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, fmt.Errorf("can't divide by zero")
}
return a / b, nil
}
Callers handle both:
result, err := divide(10, 2)
if err != nil {
fmt.Println("problem:", err)
return
}
fmt.Println(result)
Convention: the error is always the last return value, and it's always checked.
Named results
You can name the return values, which documents them and lets you
use a bare return:
func stats(nums []int) (min int, max int) {
min, max = nums[0], nums[0]
for _, n := range nums[1:] {
if n < min {
min = n
}
if n > max {
max = n
}
}
return // returns min and max
}
Use sparingly — it's nice for short functions, confusing in long
ones where the bare return hides what's coming back.
Variadic functions: any number of arguments
func sum(nums ...int) int {
total := 0
for _, n := range nums {
total += n
}
return total
}
sum(1, 2, 3) // 6
sum() // 0
...int collects extra arguments into a slice.
Functions are values
double := func(x int) int { return x * 2 }
fmt.Println(double(21)) // 42
Anonymous functions work like any other value — handy for callbacks and short helpers.
Exported vs unexported: the capitalization rule
// In package mypkg:
func Helper() { ... } // Exported — other packages can call mypkg.Helper()
func helper() { ... } // unexported — only usable inside mypkg
That's the entire access-control system: capital letter =
public, lowercase = private. It applies to functions, types,
struct fields, and constants. No public/private keywords to
memorize.
Methods (preview)
Functions attached to a type are called methods — they're covered properly in Structs and Methods. The short version:
func (u User) Greeting() string {
return "hi, " + u.Name
}
Check
- [ ] You can write a function returning two values and handle both at the call site
- [ ] You know the exported/unexported rule and where it applies
- [ ] You can explain when named results help and when they hurt
Next: Structs and Methods.