0
0
GoHow-ToBeginner · 3 min read

How to Pass Slice to Function in Go: Simple Guide

In Go, you pass a slice to a function by specifying the slice type as a parameter, like func myFunc(s []int). You can then call the function with a slice variable, and the function receives a reference to the original slice.
📐

Syntax

To pass a slice to a function, declare the function parameter with the slice type using square brackets and the element type, for example []int. This means the function accepts a slice of integers.

  • func: keyword to declare a function
  • myFunc: function name
  • s []int: parameter named s which is a slice of integers
go
func myFunc(s []int) {
    // function body
}
💻

Example

This example shows how to pass a slice of integers to a function and print each element inside the function.

go
package main

import "fmt"

func printSlice(s []int) {
    for i, v := range s {
        fmt.Printf("Element %d: %d\n", i, v)
    }
}

func main() {
    numbers := []int{10, 20, 30, 40}
    printSlice(numbers)
}
Output
Element 0: 10 Element 1: 20 Element 2: 30 Element 3: 40
⚠️

Common Pitfalls

One common mistake is trying to pass a pointer to a slice when it is not needed, since slices are already references to an underlying array. Another pitfall is modifying the slice inside the function without understanding that changes affect the original slice.

Also, passing an array instead of a slice will cause a type mismatch error.

go
package main

import "fmt"

// Wrong: passing pointer to slice unnecessarily
func wrongFunc(s *[]int) {
    (*s)[0] = 100
}

// Correct: pass slice directly
func correctFunc(s []int) {
    s[0] = 100
}

func main() {
    nums := []int{1, 2, 3}
    wrongFunc(&nums) // works but pointer not needed
    fmt.Println(nums) // [100 2 3]

    nums = []int{1, 2, 3}
    correctFunc(nums) // preferred way
    fmt.Println(nums) // [100 2 3]
}
Output
[100 2 3] [100 2 3]
📊

Quick Reference

Remember these tips when passing slices to functions:

  • Use []Type to declare slice parameters.
  • Slices are references; changes inside the function affect the original.
  • No need to pass pointers to slices unless you want to change the slice header itself.
  • Arrays and slices are different types; pass slices for flexibility.

Key Takeaways

Pass slices to functions by declaring parameters with slice types like []int.
Slices are references, so functions can modify the original slice elements.
Avoid passing pointers to slices unless you need to modify the slice header.
Arrays and slices are different; use slices for flexible and efficient passing.
Changes to slice elements inside functions affect the original slice.