Back to all posts
programming golang go

Go Slices

1 min read (139 words)

If we need a dynamic arrays - dynamically sized- go has Slices which are much more common than arrays.

Same concept, but just with no size.

[]type{}

A slice does not store any data, it just describes a section of an underlying array.

To add or change an element in an array - need to know the index, use append() - for slices

func main() {
    empty_slice := []string{} // empty slice

    s := []string{"b1", "b2", "b3", "b4", "b5"}

    // Append returns the updated slice.
    // It is necessary to store the result of append
    // often in the variable holding the slice itself
    s = append(s, "b6")

    fmt.Printf("The whole array: %v\n", s)
    fmt.Printf("The whole array: %v\n", empty_slice)
    fmt.Printf("The 1st in array: %v\n", s[0])
    fmt.Printf("The 2nd in array: %v\n", s[1])
    fmt.Printf("Array type: %T\n", s)
    fmt.Printf("Array lengh:  %v\n", len(s))
}
Go code example demonstrating slice declaration, initialization, and append operations
Dmitry Golovach
About

Dmitry Golovach

Principal Network Engineer and AI enthusiast. Always learning, always building.

Share this post

All posts