Change value in slice


We can access values in a slice and change them exactly as we do with an array. After all the slice is juts a window onto some array behind the scenes.

examples/slice-change-value/slice_change_value.go
package main

import (
    "fmt"
)

func main() {
    var dwarfs = []string{"Doc", "Grumpy", "Happy", "Sleepy", "Bashful", "Sneezy", "Dopey"}

    fmt.Println(dwarfs)
    fmt.Println(dwarfs[1])
    dwarfs[1] = "Snowwhite"

    fmt.Println(dwarfs)
    fmt.Println(dwarfs[1])

    fmt.Println(len(dwarfs))
    fmt.Println(cap(dwarfs))
}

[Doc Grumpy Happy Sleepy Bashful Sneezy Dopey]
Grumpy
[Doc Snowwhite Happy Sleepy Bashful Sneezy Dopey]
Snowwhite
7
7