![]() |
VOOZH | about |
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.
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)
}
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
}Table of Content
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.
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
[1 2 3 4 5]
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.
func modifySlice(slice []Type) {
// Modify elements in the slice
}Example
Original slice: [1 2 3 4 5] Modified slice: [2 4 6 8 10]
In Go, you can also return a modified slice from a function if needed.
func functionName(slice []Type, element Type) []Type {
// Modify and return the slice
}Example
Original slice: [1 2 3] New slice: [1 2 3 4]
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.
func modifySlicePointer(slice *[]Type) {
// Modify the slice through its pointer
}Example
Original slice: [1 2 3] Modified slice: [1 2 3 6]
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.