I want to join two lines, but I get an error message.
Original:
hash := sha1.Sum([]byte(uf.Pwd))
u.Pwhash = hex.EncodeToString(hash[:])
Joint:
u.Pwhash = hex.EncodeToString(sha1.Sum([]byte(uf.Pwd))[:])
The first one works fine, the second produces the error message:
models/models.go:104: invalid operation sha1.Sum(([]byte)(uf.Pwd))[:] (slice of unaddressable value)
Why is that?
You get an error message in the 2nd case because you try to slice the return value of a function call (that of sha1.Sum()
):
sha1.Sum(([]byte)(uf.Pwd))[:]
The return values of function calls are not addressable. As a reminder, (only) the following are addressable (taken from Spec: Address operators):
...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.
And slicing an array requires the array to be addressable. Spec: Slice expressions:
If the sliced operand is an array, it must be addressable and the result of the slice operation is a slice with the same element type as the array.
Your first case works because you first store the returned array in a local variable which is addressable.
Slicing an array requires the array to be addressable because slicing results in a slice which will not copy the data of the array but create a slice which shares the backing array and will only point/refer to it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With