Go Basics

Go Functions

Description

Functions are central to Go. They are defined with the `func` keyword. Go supports multiple return values, named return values, and variadic parameters.

Pros & Cons

✅ Pros

  • Multiple Returns: Great for error handling.
  • First-Class Citizens: Can be passed as variables.

❌ Cons

  • No Overloading: Cannot define same function name with different args.

When to Use

Structuring code.

Example

Function definition and multiple returns.

func add(x int, y int) int {
    return x + y
}

func swap(x, y string) (string, string) {
    return y, x
}

func main() {
    a, b := swap("hello", "world")
    fmt.Println(a, b)
}

Best Practices

Error handling in Go is typically done by returning an `error` as the last return value.

← Go LoopsGo Struct →