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/

相关文章:

javascript - 将变量传递给 Angular 过滤器

Bash curl POST 二进制变量

javascript - 如何从javascript中的构造函数返回字符串?

c# - SQL Server 返回代码-6,这是什么意思?

java - 有没有办法使 IF 语句中定义的变量在语句本身之外可见并可用?

Go:提供静态模板

json - 使用 Go 在 JSON 中解析包含 unicode 字符的键

Golang 超时或提前返回

c++ - 使用类和公共(public)成员优化输出值

c# - 通过事件传递变量 C#