How to pass a Slice to Function in Golang?
Last Updated :
12 Nov, 2024
In Go, slices are dynamically sized arrays. They are often passed to functions when you want to manipulate or process collections of data. Slices are passed by reference, meaning that any modification made to the slice inside the function will affect the original slice outside the function.
Example
package main
import "fmt"
func printSlice(slice []int) {
fmt.Println("Slice elements:", slice)
}
func main() {
// Initial slice
numbers := []int{1, 2, 3, 4, 5}
// Passing slice to the function
printSlice(numbers)
}
Syntax
func functionName(slice []Type) {
// Function body # Passing Slice to a Function
}
func modifySlice(slice []Type) {
// Modify elements in the slice # Modify Slice Elements inside a function
}
func functionName(slice []Type, element Type) []Type {
// Modify and return the slice # Returning a Slice from a Function
}
func modifySlicePointer(slice *[]Type) {
// Modify the slice through its pointer # Passing a Slice to a Function with a Slice Pointer
}
Passing Slice to a function
In Go, slices are passed by reference in terms of the underlying array, meaning any modification to the elements of the slice inside a function will affect the original slice, but changes to the slice’s length or capacity will not affect the original slice outside the function.
Syntax
func functionName(slice []Type) {
// Function body
}
Where:
slice
: The slice variable you want to pass.Type
: The type of elements in the slice (e.g., int
, string
, etc.).
Example
Go
package main
import "fmt"
func printSlice(slice []int) {
fmt.Println("", slice)
}
func main() {
// Initial slice
a := []int{1, 2, 3, 4, 5}
printSlice(a)
}
Modifying Slice Elements Inside a Function
You can modify the elements of the slice inside the function, and these changes will be reflected in the original slice because slices are passed by reference.
Syntax
func modifySlice(slice []Type) {
// Modify elements in the slice
}
Example
Go
package main
import "fmt"
func modifySlice(slice []int) {
for i := range slice {
slice[i] *= 2 // Doubling each element
}
}
func main() {
a := []int{1, 2, 3, 4, 5}
fmt.Println("Original slice:", a)
modifySlice(a)
fmt.Println("Modified slice:", a)
}
OutputOriginal slice: [1 2 3 4 5]
Modified slice: [2 4 6 8 10]
Returning a Slice from a Function
In Go, you can also return a modified slice from a function if needed.
Syntax
func functionName(slice []Type, element Type) []Type {
// Modify and return the slice
}
Example
Go
package main
import "fmt"
func addElement(slice []int, element int) []int {
return append(slice, element)
}
func main() {
// Initial slice
a := []int{1, 2, 3}
// Adding an element and returning the new slice
newNumbers := addElement(a, 4)
fmt.Println("Original slice:", a)
fmt.Println("New slice:", newNumbers)
}
OutputOriginal slice: [1 2 3]
New slice: [1 2 3 4]
Passing a Slice to a Function with a Slice Pointer
While slices are already passed by reference, you can also pass a pointer to a slice if you want to modify the slice’s capacity or reassign the slice inside the function.
Syntax
func modifySlicePointer(slice *[]Type) {
// Modify the slice through its pointer
}
Example
Go
package main
import "fmt"
func modifySlicePointer(slice *[]int) {
*slice = append(*slice, 6) // Adding an element using pointer
}
func main() {
// Initial slice
a := []int{1, 2, 3}
fmt.Println("Original slice:", a)
// Passing slice pointer to the function
modifySlicePointer(&a)
fmt.Println("Modified slice:", a)
}
OutputOriginal slice: [1 2 3]
Modified slice: [1 2 3 6]
Conclusion
Passing slices to functions in Go is straightforward since they are reference types. You can modify the slice elements within the function, and these changes will be reflected outside the function. You can also pass a slice pointer if you need to modify the slice’s structure, such as appending to it or changing its capacity.
Similar Reads
How to pass an Array to a Function in Golang?
In Go, arrays are used to store a fixed-length collection of data of the same type. To manage this data effectively, you may often need to pass arrays to functions. In this article we will learn "How to pass an Array to a Function in Golang". Example: [GFGTABS] Go package main import "fmt"
2 min read
How to sort a slice in Golang?
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In Go language, you can sort a s
3 min read
How to trim a slice of bytes in Golang?
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice of bytes, you ar
4 min read
How to sort a slice of float64s in Golang?
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. Go language allows you to sort t
3 min read
How to split a slice of bytes in Golang?
In Golang, you can split a slice of bytes into multiple parts using the bytes.Split function. This is useful when dealing with data like encoded strings, file contents, or byte streams that must be divided by a specific delimiter. Examplepackage mainimport ( "bytes" "fmt")func main() { // Initial by
3 min read
How to repeat a slice of bytes in Golang?
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice of bytes, you ar
3 min read
How to sort a slice of ints in Golang?
In Go, slices provide a flexible way to manage sequences of elements. To sort a slice of ints, the sort package offers a few straightforward functions. In this article we will learn How to Sort a Slice of Ints in Golang. Example [GFGTABS] Go package main import ( "fmt" "sort" ) f
2 min read
How to append a slice in Golang?
In Go, slices are dynamically-sized, flexible views into the elements of an array. Appending elements to a slice is a common operation that allows for the expansion of the slice as needed. The built-in append function is used to add elements to the end of a slice.In this article,we will learn How to
2 min read
How to compare two slices of bytes in Golang?
In Go, a slice is a powerful, flexible data structure that allows elements of the same type to be stored in a variable-length sequence. When working with byte slices ([]byte), Go provides easy-to-use functions in the bytes package to compare them. In this article we will learn "How to compare two sl
2 min read
How to use strconv.Quote() Function in Golang?
Go language provides inbuilt support to implement conversions to and from string representations of basic data types by strconv Package. This package provides a Quote() function which is used to find a double-quoted Go string literal representing str and the returned string uses Go escape sequences
2 min read