Skip to main content
Functions are central to Go programming. They allow you to organize code into reusable blocks that perform specific tasks.

Basic Function Syntax

In Go, functions are defined using the func keyword, followed by the function name, parameters, return type, and body.
func plus(a int, b int) int {
    return a + b
}
This function:
  • Takes two parameters a and b, both of type int
  • Returns a single int value
  • Uses an explicit return statement
Go requires explicit returns. Unlike some languages, Go won’t automatically return the value of the last expression.

Parameter Type Shorthand

When multiple consecutive parameters share the same type, you can omit the type name for all but the final parameter:
// Instead of: func plusPlus(a int, b int, c int) int
func plusPlus(a, b, c int) int {
    return a + b + c
}
This shorthand syntax makes function signatures more concise while maintaining clarity.

Calling Functions

Functions are called using the familiar name(args) syntax:
func main() {
    res := plus(1, 2)
    fmt.Println("1+2 =", res)
    // Output: 1+2 = 3

    res = plusPlus(1, 2, 3)
    fmt.Println("1+2+3 =", res)
    // Output: 1+2+3 = 6
}

Complete Example

package main

import "fmt"

// Basic function with two parameters
func plus(a int, b int) int {
    return a + b
}

// Function with parameter type shorthand
func plusPlus(a, b, c int) int {
    return a + b + c
}

func main() {
    res := plus(1, 2)
    fmt.Println("1+2 =", res)

    res = plusPlus(1, 2, 3)
    fmt.Println("1+2+3 =", res)
}

Best Practices

Choose names that clearly describe what the function does. Use camelCase for unexported functions and PascalCase for exported functions.
Each function should do one thing well. If a function is doing too much, consider breaking it into smaller functions.
Go requires explicit return statements, which makes code more readable and less prone to errors.

Key Takeaways

  • Functions are defined with the func keyword
  • Parameter types can be shared using shorthand syntax
  • Go requires explicit return statements
  • Functions are called using standard name(args) syntax

Build docs developers (and LLMs) love