How to return an array to the function in Golang?


In programming, to make the code more modular, usable, and readable we break the code into different functions. For example, we have to swap two numbers at different places so instead of swapping in place we create a different function and call it everywhere. In some use cases, we need a function that returns multiple values at once. For this, we have a data structure called arrays in programming that is nothing but a collection of multiple values of the same type. In this tutorial, we are going to learn about how to return an array in function as an argument in Golang.

Example 

In this example, we are going to pass an array of integer types in the function and then sort the array and in the end, return the sorted array. To sort the array we are going to use the selection sort algorithm.

Algorithm

  • Step 1: var array [5]int − Declare a variable of size 5 and data type int.

  • Step 2: array[0] = 45, array[1] = 9, array[2] = 99, array[3] = 900, array[4] = 801 − Initializing all the indexes of the array.

  • Step 3: array = sortTheArray(array) − Sort the array by using the selection sort. First, we call the function and pass the array initialized above, and then sort the array.

    • for i := 0; i < len(array)−1; i++ { } − Running a for loop from 0 to length −1 of the array.

    • min_index := i − Create a variable on each iteration to store the index of the smallest number in the remaining elements.

    • for j := i + 1; j < len(array); j++ { } − Running an inner loop from i + 1 till the last index of the array.

    • if array[j] < array[min_index] { min_index = j } − Adding an if statement to find the minimum element in the remaining element and storing the index in min_index.

    • if i != min_index { swap(&array[i], &array[min_index]) } − Here we are doing swapping if the value of min_index is changed in the inner loop.

  • Step 4: Print the sorted array.

Example

package main

import (
    // fmt package provides the function to print anything
    "fmt"
)

func swap(number1, number2 *int) {
    // swapping both numbers using the third number
    number3 := *number1
    *number1 = *number2
    *number2 = number3
}

// array is the argument in this function
func sortTheArray(array [5]int) [5]int {
    fmt.Println("Sorting the array using the Selection sort algorithm.")

    // running a for loop from 0 to 1 less than the array length
    for i := 0; i < len(array)-1; i++ {
        // declaring and initializing the variable that will store the index
        // of minimum element in the remaining element
        min_index := i

        // running an inner loop on the elements after ith index
        for j := i + 1; j < len(array); j++ {
            // comparing the element with the element at min_index
            if array[j] < array[min_index] {
                min_index = j
            }

        }

        // swapping the elements if i and min_index does not matches
        if i != min_index {
            swap(&array[i], &array[min_index])
        }
    }

    return array
}

func main() {
    // declaring the array of type string with size 5
    var array [5]int

    // initializing all the index of array
    array[0] = 45
    array[1] = 9
    array[2] = 99
    array[3] = 900
    array[4] = 801

    fmt.Println("Golang program to return an array in the function.")
    fmt.Println("Array elements before sorting.")

    for i := 0; i < len(array); i++ {
        fmt.Printf("%d ", array[i])
    }
    fmt.Println()

    // passing argument in the function and storing the returned
    // sorted array in the array variable
    array = sortTheArray(array)

    fmt.Println("Array elements after sorting.")
    for i := 0; i < len(array); i++ {
        fmt.Printf("%d ", array[i])
    }
    fmt.Println()
}

Output

Golang program to return an array in the function.
Array elements before sorting.
45 9 99 900 801 
Sorting the array using the Selection sort algorithm.
Array elements after sorting.
9 45 99 801 900

Conclusion

This is the example of returning an array from the function in Golang where we have passed an array of type int to a function and then sort the array using selection sort. After sorting the array we returned the array in the end. To learn more about Go you can explore these tutorials.

Updated on: 10-Jul-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements