Slices
Array
Go’s arrays are values (value type) means whenever you assign an array to a new variable then the copy of the original array is assigned to the new variable.
This is also called as deep copy.
The main issue an array has is that it can not be resized.
Arrays do not need to be initialised explicitly; the zero value of an array is a ready-to-use array whose elements are themselves zeroed:
To overcome this problem we have Slices in golang.
package main
import "fmt"
func main() {
// Declare and initialize an array of integers
var numbers [5]int
numbers[0] = 1
numbers[1] = 2
numbers[2] = 3
numbers[3] = 4
numbers[4] = 5
// Access and print values from the array
fmt.Println("numbers[0]:", numbers[0])
fmt.Println("numbers[2]:", numbers[2])
fmt.Println("numbers:", numbers)
// Declare and initialize an array of strings
names := [3]string{"Alice", "Bob", "Charlie"}
// Access and print values from the array
fmt.Println("names[1]:", names[1])
fmt.Println("names:", names)
// Determine the length of an array
fmt.Println("Length of numbers array:", len(numbers))
fmt.Println("Length of names array:", len(names))
}
Slices
Slices are the wrapper over arrays.
Slices do not own any data of their own, they are just a reference to the existing array.
Slices have length and capacity. Length is the number of elements present in the slice,
Capacity is the number of elements present in the underlying array.
New elements can be added to the slice using append function.
package main
import "fmt"
func main() {
// Create a slice of integers
numbers := []int{1, 2, 3, 4, 5}
// Access and print values from the slice
fmt.Println("numbers[0]:", numbers[0])
fmt.Println("numbers[2]:", numbers[2])
fmt.Println("numbers:", numbers)
// Modify a value in the slice
numbers[1] = 10
fmt.Println("Modified numbers:", numbers)
// Create a slice using make()
names := make([]string, 3)
names[0] = "Alice"
names[1] = "Bob"
names[2] = "Charlie"
// Access and print values from the slice
fmt.Println("names[1]:", names[1])
fmt.Println("names:", names)
// Append values to the slice
names = append(names, "Dave", "Eve")
fmt.Println("Appended names:", names)
// Slicing a slice
sliced := numbers[1:4]
fmt.Println("Sliced numbers:", sliced)
// Length and capacity of a slice
fmt.Println("Length of numbers slice:", len(numbers))
fmt.Println("Capacity of numbers slice:", cap(numbers))
}
Memory Allocation of slices :
When the slice length is equal to its capacity and you try to append a new element to it,
then the new memory is allocated to the slice which has the double capacity as compared to the earlier capacity.
Slices are an important data structure in Go and are used extensively in many programs.
They are a flexible and efficient way to work with arrays and can save you time and effort when coding in Go.