EZ

Eduzan

Learning Hub

Eduzan
Eduzan / Go Programming Language

Slices in Golang

What Are Slices?

  • Slices are a flexible and dynamic abstraction over arrays in Go.
  • They represent a contiguous segment of an array and include a pointerlength, and capacity.
  • Unlike arrays, slices are resizable.

Key Features:

  1. Dynamic Size: Unlike arrays, slices can grow or shrink as required.
  2. Reference Type: Slices point to an underlying array. Changes to the slice affect the array and vice versa.
  3. Homogeneous Elements: Slices can only hold elements of the same type.
  4. Support for Duplicates: Slices can contain duplicate elements.

Slice Components:

  1. Pointer: Points to the starting element of the slice.
  2. Length: Number of elements in the slice.
  3. Capacity: Maximum number of elements the slice can accommodate without reallocation.

Creating Slices:

1. From Arrays: Use slicing syntax array[low:high].

2. Slice Literals:

mySlice := []int{1, 2, 3}

3. Using make():

mySlice := make([]int, length, capacity)

4. From Existing Slices: Use slicing syntax on slices.

Array elements:
10
20
30
40
50

Examples:

1. Basic Slicing:

arr := [5]int{1, 2, 3, 4, 5}
slice := arr[1:4]
fmt.Println(slice) // Output: [2 3 4]

2: Using append():

slice := []int{1, 2}
slice = append(slice, 3, 4)
fmt.Println(slice) // Output: [1 2 3 4]

3. Using make():

slice := make([]int, 3, 5)
fmt.Println(slice) // Output: [0 0 0]

4. Iterating Over Slices:

  • Using for loop:
for i := 0; i < len(slice); i++ {
    fmt.Println(slice[i])
}
  • Using range:
for idx, val := range slice {
    fmt.Printf("Index: %d, Value: %d\n", idx, val)
}

Output:

Colors in the array:
Red
Green
Blue
End of lesson.