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

编程入门 行业动态 更新时间:2024-10-17 21:16:58
本文介绍了变量和函数返回值的不同行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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.

更多推荐

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

本文发布于:2023-11-15 23:31:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1598934.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   函数   返回值

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!