Slices in Golang: Usage and examples
This article explains how to work with slices in Golang, including how to declare, access, and manipulate slices—a flexible way to handle arrays more efficiently in Go.
In Golang, slices are a special type of array that allows you to work with portions of an array without copying them. Slices are more flexible and easier to manage compared to traditional arrays, especially when dealing with dynamic data.
Golang Code
package main
import "fmt"
func main() {
// Declare an initial array
arr := [5]int{1, 2, 3, 4, 5}
// Create a slice from the array
slice := arr[1:4]
// Print the elements of the slice
fmt.Println("Slice:", slice)
// Modify an element in the slice
slice[0] = 10
// Print the original array after modifying the slice
fmt.Println("Original array:", arr)
// Append an element to the slice using append
slice = append(slice, 6)
// Print the slice after appending
fmt.Println("Slice after append:", slice)
}
Detailed explanation:
arr := [5]int{1, 2, 3, 4, 5}
: Creates an array with 5 elements.slice := arr[1:4]
: Creates a slice from the arrayarr
, taking elements from index 1 to 3 (excluding index 4).fmt.Println("Slice:", slice)
: Prints the elements of the slice.slice[0] = 10
: Modifies the first element of the slice.fmt.Println("Original array:", arr)
: Prints the original array to show that the slice shares memory with the array.slice = append(slice, 6)
: Appends a new element to the slice using theappend
function.fmt.Println("Slice after append:", slice)
: Prints the slice after appending the new element.
Tips:
- Slices share memory with the original array, so modifying the slice affects the array as well.
- When using
append
, if the slice does not have enough memory, a new array will be created to store the data.