我想连接两行,但收到错误消息。
原文:
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/