dp19001 2017-12-08 21:38
浏览 890
已采纳

Go中的[:]符号是什么意思?

I found this in some code:

h := s.Hash(tx)
sig, err := crypto.Sign(h[:], prv)

What does [:] mean ? If this is the full slice of the array, why not to pass the array itself? What kind of coding style is this, I wonder...

  • 写回答

1条回答 默认 最新

  • dongwei2983 2017-12-08 21:49
    关注

    In go, Arrays and Slices are slightly different and cannot be used interchangeably; however, you can make a slice from an array easily using the [:] operator.

    This article explains in detail - Go Slices: Usage and Internals.

    See also the Slice Expressions section of The Go Programming Language Specification.

    In a nutshell, the [:] operator allows you to create a slice from an array, optionally using start and end bounds. For example:

    a := [3]int{1, 2, 3, 4} // "a" has type [4]int (array of 4 ints)
    x := a[:]   // "x" has type []int (slice of ints) and length 4
    y := a[:2]  // "y" has type []int, length 2, values {1, 2}
    z := a[2:]  // "z" has type []int, length 2, values {3, 4}
    m := a[1:3] // "m" has type []int, length 2, values {2, 3}
    

    Presumably the reason for this distinction is for an extra measure of type safety. That is, length is a formal part of an array type (e.g. [4]int is an array of four ints and a different size is a different type) whereas slices can have any length, including zero. So if you want the safety of a known-length sequence then use an Array, otherwise use a Slice for convenience.

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

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办