Go Slice Expressions: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 41: Line 41:


Equivalent with <code>[i:len(slice)]</code>.
Equivalent with <code>[i:len(slice)]</code>.
==<tt>[:i]</tt>==
Equivalent with <code>[0:i]</code>.
==<tt>[:]</tt>==
Means the slice itself, which is useful when slicing an array. To turn an entire array into a slice:
<syntaxhighlight lang='go'>
array[:]
</syntaxhighlight>


=Idiomatic Use Cases=
=Idiomatic Use Cases=

Revision as of 00:40, 24 August 2024

Internal

TODO

Overview

Slice expressions can be used on array or other slices.

A slice expression applied to a slice creates a new slice that shares the underlying array with the original slice. Applying a slice expression to a slice is called reslicing.

ss := make([]int, 10) // declare a slice with length and capacity 10, initialized with 0
ss2 := ss[3:6]

    ┌─────────────────────┐
 ss │pointer,len=10,cap=10│
    └──│──────│──────│────┘
       │      └──────┴──────────────────────────┐
       └──────────────────────┐                 │
                              ▼                 ▼
                             ┌─┬─┬─┬─┬─┬─┬─┬─┬─┬─┐
             derlying array  └─┴─┴─┴─┴─┴─┴─┴─┴─┴─┘
                              0 1 2 3 4 5 6 7 8 9
                                    ▲   ▲       ▲
        ┌───────────────────────────┘   │       │
        │      ┌────────────────────────┘       │
        │      │     ┌──────────────────────────┘
    ┌───│──────│─────│────┐    
ss2 │ pointer,len=3,cap=7 │
    └─────────────────────┘

The slice expression creates a different slice that provides access to the elements with indexes 3, 4, 5 of the underlying array. Both slices ss and ss2 provide access to those elements and changes operated via one slice are visible to the other.

The length of the second slice is the number of elements defined by the slice expression (3). However, since the slices share the same underlying array, the capacity of the second slice is the number of elements from the element with index 3 to the end of the underlying array: 7.

Shorthands

[i:]

Equivalent with [i:len(slice)].

[:i]

Equivalent with [0:i].

[:]

Means the slice itself, which is useful when slicing an array. To turn an entire array into a slice:

array[:]

Idiomatic Use Cases

Truncate a Slice

Drop the First Element

slice := slice[1:len(slice)]

Equivalent with:

slice := slice[1:]

Drop the Last Element

slice := slice[0:len(slice)-1]