Sling Academy
Home/Golang/Understanding Function Parameters and Return Values in Go

Understanding Function Parameters and Return Values in Go

Last updated: November 26, 2024

In the Go programming language, functions are a fundamental part of structuring code and managing complexity. In this article, we'll explore function parameters and return values, critical aspects of Go functions.

Function Parameters

Function parameters allow you to pass values into functions. In Go, parameters can have names and are followed by their type. Let's delve into some basic to advanced usage.

Basic Usage

Code Example 1: Single Parameter


// language: Go
package main

import "fmt"

func greet(name string) {
    fmt.Printf("Hello, %s!\n", name)
}

func main() {
    greet("Alice")
}

In this basic example, the greet function takes a single parameter, name, of type string.

Intermediate Usage

Code Example 2: Multiple Parameters


// language: Go
package main

import "fmt"

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

func main() {
    sum := add(5, 3)
    fmt.Println("Sum:", sum)
}

This intermediate example shows the add function with two parameters, x and y, both of type int. The function returns their sum.

Variadic Functions

Go also supports variadic functions, which can take an arbitrary number of parameters.

Code Example 3: Variadic Function


// language: Go
package main

import "fmt"

func sum(numbers ...int) int {
    total := 0
    for _, number := range numbers {
        total += number
    }
    return total
}

func main() {
    fmt.Println("Sum:", sum(1, 2, 3, 4, 5))
}

The sum function receives a slice of int through a variadic parameter and computes their total.

Function Return Values

Functions in Go can return values, and specifying return types is a part of the function's signature. Let's look at the different ways to handle return values.

Basic Return

Code Example 4: Single Return Value


// language: Go
package main

import "fmt"

func multiply(a int, b int) int {
    return a * b
}

func main() {
    product := multiply(3, 4)
    fmt.Println("Product:", product)
}

This function multiply multiplies two integers and returns the product.

Intermediate Return

Code Example 5: Multiple Return Values


// language: Go
package main

import "fmt"

func divide(x, y int) (int, int) {
    quotient := x / y
    remainder := x % y
    return quotient, remainder
}

func main() {
    q, r := divide(5, 2)
    fmt.Println("Quotient:", q, "Remainder:", r)
}

This example highlights a function that returns multiple values, useful for operations like division where both quotient and remainder are needed.

Named Return Values

In advanced usage, Go allows naming the return values in the function signature and using them explicitly in the function body.

Code Example 6: Named Returns


// language: Go
package main

import "fmt"

func calculateRectangle(length, width int) (area, perimeter int) {
    area = length * width
    perimeter = 2 * (length + width)
    return // implicit return of named values
}

func main() {
    area, perimeter := calculateRectangle(5, 3)
    fmt.Println("Area:", area, "Perimeter:", perimeter)
}

Here, the function calculateRectangle uses named return values area and perimeter, making the code more readable.

Next Article: Using Named Return Values for Cleaner Code in Go

Previous Article: Defining and Calling Functions in Go: A Beginner's Guide

Series: Functions in Go

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant