×

Go Tutorial

Go Basics

Go Variables

Go Literals

Go Type Handling

Go Operators

Go Decision Making

Go Loops

Go Functions

Go String

Go Arrays

Go Slices

Go Maps

Go Pointers

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Go Pass a Slice to Function

Last Updated : July 21, 2025

In Go, slices are passed to functions by reference, meaning that any modification made to the slice within the function will affect the original slice.

Passing a Slice to a Function

You can pass a slice as a parameter to a function just like any other data type. Since slices internally contain a pointer to the underlying array, the function receives a copy of the slice header but points to the same underlying data.

Example

This example demonstrates how changes inside a function affect the original slice:

package main
import "fmt"

func modifySlice(s []int) {
    s[0] = 100
    s = append(s, 999) // Appending creates a new underlying array if capacity exceeds
    fmt.Println("Inside function:", s)
}

func main() {
    nums := []int{1, 2, 3}
    modifySlice(nums)
    fmt.Println("In main:", nums)
}

When you run the above code, the output will be:

Inside function: [100 2 3 999]
In main: [100 2 3]

Explanation

  • The value at index 0 is changed to 100 and is reflected outside the function.
  • The append() may allocate a new array if needed, so the new element 999 is not seen in main.

Appending to Slice Inside Function

If you want to reflect appended elements outside the function, return the modified slice and assign it back.

Example

package main
import "fmt"

func addElement(s []int) []int {
    s = append(s, 10)
    return s
}

func main() {
    data := []int{1, 2, 3}
    data = addElement(data)
    fmt.Println("Updated slice:", data)
}

When you run the above code, the output will be:

Updated slice: [1 2 3 10]

Difference Between Array and Slice Parameters

Unlike arrays, slices allow dynamic resizing and naturally refer to shared data. Arrays, when passed to functions, behave like value types (copied entirely).

Key Points

  • Slices are reference types – changes to elements inside a function are visible outside.
  • Appending inside a function may create a new array – changes won’t affect the original slice unless reassigned.
  • Use return values if you want to keep structural changes like appended elements.

Go Pass a Slice to Function Exercise

Select the correct option to complete each statement about passing slices to functions in Go.

  1. When you pass a slice to a function, it:
  2. If you append to a slice inside a function, the change:
  3. Which of the following is true?

Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

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