Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different behavior of variable and return value of function

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?

like image 387
Michael Avatar asked Feb 09 '23 22:02

Michael


1 Answers

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.

like image 58
icza Avatar answered Feb 11 '23 21:02

icza