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/32818994/

相关文章:

Ruby 变量引用其他变量

go - 如何在gin请求上下文中设置数据?

golang 有效地处理 Null* 类型

latex - 我可以将LaTeX宏 'return'设为文件名吗?

java - 为什么我的返回值在我的 main 方法中没有保存值?

php - 如何使php post变量唯一

javascript - 在点击 jquery 事件中找不到变量

go - 可变 slice 作为参数错误 :cannot initialize 2 variables with 1 value

c - 函数返回值的 `rc` 是什么意思?

javascript - 在 JavaScript 中引用复杂变量