Slice to slice assignments

Hi everybody,

I am new to the Go language and trying to understand some concepts. I have the following piece of code & func appendInto:

I think what my code does is pretty clear, so I suppose no need to explain. My question is why in func appendInto subslice assignment (line 37) gives a compile-time error? I referred to the corresponding Effective Go paragraph about the slice assignments inside the piece of my code. Even though it is the wrong statement to use for my purpose, I would expect this to be a valid action since it should assign the array list1 to finalList?

So what am I really missing here?

Thanks in advance.

It gives a compile-time error because assignment requires that the left hand side either be addressable or a map indexing expression, and slice expressions are not addressable. To make assignments to subslices work, the compiler would have to translate the = operator for slices into a call to copy. I don’t think this will ever happen because you could just write the call to copy yourself.

Slices are essentially the following structure*:

type stringSlice4 struct {
    data *[4]string
    length int
    capacity int

So your code essentially does this: The Go Playground

If we stick with that example, slicing a []string (e.g. subslice := list1[1:2]) essentially translates into the following**:

subslice := stringSlice4{
    data: &[1],
    length: 1,
    capacity: 2,

So a slicing expression computes and returns a new slice which is a compound data type.

Assigning to a subslice (e.g. finalList[:len(list1)] = list1[:]) would translate to this:

    length: list1.Len(),
} = list1

Which doesn’t make sense. What you’re really looking for is a way to copy the elements from list1 into another slice, which is exactly what the copy function is for.

* Assuming the element type of the slice is string and cap(slice) == 4.
** This won’t actually compile because Go’s array lengths are part of their type. Slices and maps are “magic” types in that the compiler and the runtime know how to dynamically handle the slice lengths.


Thanks for the answer. As far as I understood the issue was with the addressability of the left hand side of the assignment. :+1:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.