douxing9567 2015-09-28 08:49
浏览 51
已采纳

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

I want to join two lines, but I get an error message.

Original:

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

Joint:

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)

Why is that?

  • 写回答

1条回答 默认 最新

  • douci2022 2015-09-28 08:55
    关注

    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):

    ...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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计