Lesson 5 of 18

Functions

Functions in Go

Functions are declared with func, followed by the name, parameters, and return type:

func greet(name string) string {
    return "Hello, " + name
}

Parameter types come after the name, not before. This was a deliberate choice. The Go team believes it reads more naturally, especially as declarations get complex.

When consecutive parameters share a type, you can group them:

func add(a, b int) int {
    return a + b
}

Multiple Return Values

"She canna take much more of this, Captain!" Scotty always had a function for every crisis --- and in Go, functions can even return multiple values at once.

This is one of Go's most distinctive features. A function can return more than one value:

func divide(a, b float64) (float64, error) {
    if b == 0 {
        return 0, fmt.Errorf("division by zero")
    }
    return a / b, nil
}

The caller unpacks the results:

result, err := divide(10, 3)

This pattern is the foundation of Go's error handling. Instead of exceptions, functions return errors as values.

Named Return Values

You can name your return values, which documents what the function returns and allows "naked" returns:

func swap(a, b string) (first, second string) {
    first = b
    second = a
    return // returns first and second
}

Use named returns sparingly. They are most useful for documenting return values in short functions. In longer functions, explicit returns are clearer.

Functions as Values

Functions are first-class values. You can assign them to variables, pass them as arguments, and return them from other functions:

double := func(x int) int {
    return x * 2
}
fmt.Println(double(5)) // 10

Your Task

Write a function minMax that takes a []int and returns two int values: the minimum and the maximum values from the slice.

Go runtime loading...
Loading...
Click "Run" to execute your code.