variables - 变量的不同行为和函数的返回值

标签 variables go return-value slice

我想连接两行,但收到​​错误消息。

原文:

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

联合:

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

第一个工作正常,第二个产生错误消息:

models/models.go:104: invalid operation sha1.Sum(([]byte)(uf.Pwd))[:] (slice of unaddressable value)

这是为什么?

最佳答案

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

sha1.Sum(([]byte)(uf.Pwd))[:]

函数调用的返回值是不可寻址的。提醒一下,(仅)以下内容是可寻址的(取自 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.

并且 slice 数组需要数组是可寻址的。 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.

您的第一个案例之所以有效,是因为您首先将返回的数组存储在可寻址的局部变量中。

slice 数组需要数组是可寻址的,因为 slice 会导致 slice 不会复制数组的数据,而是创建一个共享后备数组的 slice ,并且只会指向/引用它。

关于variables - 变量的不同行为和函数的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52799340/

相关文章:

go - 如何使用带有环境变量或相对路径的替换指令

c++ - 使用 atan2() 函数进行模拟时出现奇怪的 "yaw"行为

php - 使用选择器时传递函数参数的好方法是什么?

go - 如何在 slice 中分配动态类型

scala - 在 Scala 中,我如何显式引用封闭的本地范围?

json - 解码不同 JSON 映射中的结构

javascript - 如何在变量 JavaScript 中保存递归函数的返回值

Scheme 如何返回多个值?

python-3.x - python 声明值的简单方法

php - 将 IF 条件放入变量中