Different behavior of variable and return value of function

喜欢而已 提交于 2019-12-01 18:55:34

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.

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