sahaj
sahaj

Reputation: 842

Understanding slice assignment in Go

In the below code snippet, what exactly is the line after the if block doing

slice = slice[0:l+len(data)]?

func Append(slice, data []byte) []byte {
    l := len(slice)
    if l + len(data) > cap(slice) {  // reallocate
        // Allocate double what's needed, for future growth.
        newSlice := make([]byte, (l+len(data))*2)
        // The copy function is predeclared and works for any slice type.
        copy(newSlice, slice)
        slice = newSlice
    }
    slice = slice[0:l+len(data)]  // <-- What is this doing ?
    for i, c := range data {
        slice[l+i] = c
    }
    return slice
}

Upvotes: 2

Views: 6780

Answers (3)

DarkLighting
DarkLighting

Reputation: 307

Just posting this answer for future reference.

That line has no use. The slice's capacity was extended by the statements right above it.

        // Allocate double what's needed, for future growth.
        newSlice := make([]byte, (l+len(data))*2)
        // The copy function is predeclared and works for any slice type.
        copy(newSlice, slice)
        slice = newSlice

The first line created a bigger slice called "newSlice".
In the second one "slice" had its content copied to "newSlice".
And then, "newSlice" was kind of cloned back to "slice".

Yeah, Go does feel strange about this thing, as not also the content is copied, but "slice" now has the same capacity as "newSlice". But it is not like a "pointer assignment" in C, as we still have two different slice instances and what happens to one doesn't affect the other. Please note the usage of the assignment operator "=" instead of the short variable declaration operator ":=", as noted in this answer in SO

What was actually done was the assignment of the original "slice" values and "0" to the "newSlice" extra positions, but it was also a waste, as Go had already initialized them as "0" in the make() statement.

It was also a second waste, as the loop right after it redefined all those positions along with the rest of the content in "data". This link may help with the loop meaning.

So, the line has no use at all and you should remove it.

Upvotes: 0

chen peng
chen peng

Reputation: 1

just expand the len(slice) ,so can append data, remove this this statement, slice out of index occurs...In addition,copy return the min len(src) and len(dst), so when execute if l + len(data) > cap(slice),the len(slice) would be 0

Upvotes: 0

gorros
gorros

Reputation: 1461

I guess

slice = slice[0:l+len(data)] 

changes slice length, so you can add new elements.

You can extend a slice's length by re-slicing it, provided it has sufficient capacity.

reference

Upvotes: 2

Related Questions