Reputation: 1681
I believe there is a slight problem with the Go specification. The following complains that the array literal is not addressable:
print([4]int{2,3}[:2])
I know why an array returned from a function is not addressable (eg Error addressing the returned slice of a function) but why is an array literal like [4]int{2,3}
not addressable? Especially when slice and string literals are - eg these work fine:
print([]int{2,3,0,0}[:2])
print("2300"[:2])
Moreover, array literals do seem to be addressable since &[4]int{42,43}
is a valid expression.
I know I can use a slice
print([]int{2,3,0,0}[:2])
but what if I wanted the capacity (array length) to be a compile-time constant.
const maxLength = 4
...
print([maxLength]int{2,3}[:2])
And yes I can assign to a temporary array variable, but why do I need to?
Upvotes: 0
Views: 367
Reputation: 121049
Use the following:
fmt.Println((&[4]int{2, 3})[:2])
The specification says this about slice expressions:
If the sliced operand is an array, it must be addressable.
and this about addressability:
The operand must be addressable, that is, either a variable, pointer indirection, or slice indexing operation; or a field selector of an addressable struct operand; or an array indexing operation of an addressable array. As an exception to the addressability requirement, x may also be a (possibly parenthesized) composite literal.
The array is not addressable, but the composite literal exception can be used to get an addressable value.
Array operands must be addressable because the elements of the resulting slice are addressable. String operands are not required to be addressable because string elements are never addressable.
Upvotes: 5