×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Go Language - Passing Array to a Function

In Go, arrays can be passed to functions as arguments. However, when an array is passed to a function, it is passed by value, meaning a copy of the array is made. To modify the original array, a pointer or slice should be used.

Passing an Array by Value

By default, Go passes arrays by value, meaning that any modifications inside the function do not affect the original array.

Example

package main
import "fmt"

// Function to print an array
func printArray(arr [5]int) {
    for _, value := range arr {
        fmt.Print(value, " ")
    }
    fmt.Println()
}

func main() {
    numbers := [5]int{1, 2, 3, 4, 5}
    printArray(numbers)
}

When executed, this program outputs:

1 2 3 4 5 

Passing an Array by Reference

To modify the original array inside a function, a pointer to the array should be used.

Example

package main
import "fmt"

// Function to modify an array
func modifyArray(arr *[3]int) {
    arr[0] = 100 // Modifying the first element
}

func main() {
    numbers := [3]int{1, 2, 3}
    modifyArray(&numbers)
    fmt.Println(numbers)
}

When executed, this program outputs:

[100 2 3] 

Using Slices Instead of Arrays

Since slices are passed by reference, modifications made inside a function affect the original data.

Example

package main
import "fmt"

// Function to modify a slice
func modifySlice(s []int) {
    s[0] = 200 // Modifying the first element
}

func main() {
    numbers := []int{10, 20, 30}
    modifySlice(numbers)
    fmt.Println(numbers)
}

When executed, this program outputs:

[200 20 30] 
Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement



Copyright © 2024 www.includehelp.com. All rights reserved.