Slices let you work with lists of items easily and efficiently. They help you handle groups of data without fixing the size in advance.
0
0
Why slices are used in Go
Introduction
When you need a list that can grow or shrink during the program.
When you want to pass a part of an array without copying all data.
When you want to share data between functions without extra memory use.
When you want to work with dynamic collections like user inputs or file lines.
Syntax
Go
var s []int s = []int{1, 2, 3} s = append(s, 4)
Slices are like windows to arrays; they do not store data themselves but point to arrays.
You can add items to slices using append, which creates a bigger underlying array if needed.
Examples
Create a slice with three numbers.
Go
var numbers []int numbers = []int{10, 20, 30}
Add a new number to the slice.
Go
numbers = append(numbers, 40)Create a slice that views part of the original slice.
Go
part := numbers[1:3]
Sample Program
This program shows how to create a slice, add an item, and print all items. It demonstrates slices' flexibility to grow.
Go
package main import "fmt" func main() { // Create a slice of strings fruits := []string{"apple", "banana", "cherry"} // Add a new fruit fruits = append(fruits, "date") // Print all fruits for i, fruit := range fruits { fmt.Printf("Fruit %d: %s\n", i+1, fruit) } }
OutputSuccess
Important Notes
Slices are more flexible than arrays because their size can change.
When you pass a slice to a function, it shares the same underlying array, so changes affect the original data.
Summary
Slices let you work with lists that can change size.
They point to arrays but are easier to use and more flexible.
Use slices to handle dynamic data efficiently.