John
John

Reputation: 329

Slice order guarantee based on order of insertion

This is super trivial question but I could not find it asked here. Sorry if I missed it.

Can I count that the order in slice is always the order of insertion of elements in that slice? I tested it with the following code:

func main() {
    for i := 0; i < 10000; i++ {
        testOrder()
    }
}

func testOrder() {
    sl := []int{}
    for i := 0; i < 50; i++ {
        sl = append(sl, i)
    }
    for i, el := range sl {
        if el != i {
            panic("Order not quaranteed")
        }
    }
}

Fill a slice with numbers and then check if the order of elements in the slice is as they were populated in it. I do this check 10000 times.

Upvotes: 1

Views: 3624

Answers (2)

Burak Serdar
Burak Serdar

Reputation: 51512

Slices and arrays are sequentially ordered structures. The order of elements will never change if you append to them, even if they are copied in memory.

Upvotes: 2

icza
icza

Reputation: 417572

You're not inserting but appending. append() always appends the elements to the end of the slice, and it does not leave "holes". So yes, you can count on that your example will never panic with "Order not guaranteed".

Read more about the append() function in its doc: https://golang.org/pkg/builtin/#append

Also in the Spec: Appending to and copying slices

Also read official blog post: The Go Blog: Arrays, slices (and strings): The mechanics of 'append'

Upvotes: 9

Related Questions