Different behavior of variable and return value of function

和自甴很熟 提交于 2019-12-01 21:23:44

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/32818994/different-behavior-of-variable-and-return-value-of-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!