Gaaker Go

Golang Access and change of slice elements

The slice element is accessed or changed its value by index.

A slice is a reference to a fragment of an array and does not store any value itself. This means that any changes in the original array will be reflected in the slice, and vice versa.

The following is a complete code example.

package main

import "fmt"

func main() {
    array := [5]int{1, 2, 3, 4, 5}
    slice := array[1:4]
	fmt.Printf("Array=%v, Slice=%v\n", array, slice)

    slice[0] = -2
	fmt.Printf("Modifying Slice: Array=%v, Slice=%v\n", array, slice)

    array[1] = 2
    fmt.Printf("Modifying Array: Array=%v, Slice=%v\n", array, slice)
}

Below is the program output:

Array=[1 2 3 4 5], Slice=[2 3 4]
Modifying Slice: Array=[1 -2 3 4 5], Slice=[-2 3 4]
Modifying Array: Array=[1 2 3 4 5], Slice=[2 3 4]
< Access and change of slice elements Access and change of slice elements >