变量和函数返回值的不同行为 [英] Different behavior of variable and return value of function

查看:54
本文介绍了变量和函数返回值的不同行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想加入两行,但收到​​错误消息.

I want to join two lines, but I get an error message.

原文:

hash := sha1.Sum([]byte(uf.Pwd))
u.Pwhash = hex.EncodeToString(hash[:])

联合:

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)

那是为什么?

推荐答案

在第二种情况下,您会收到一条错误消息,因为尝试对函数调用的返回值(sha1.Sum()的返回值)进行切片:

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):

...变量,指针间接寻址或切片索引操作;或可寻址结构操作数的字段选择器;或可寻址数组的数组索引操作.作为可寻址性要求的例外,x也可以是(可能带有括号)复合文字.

...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.

这篇关于变量和函数返回值的不同行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆