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

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

图片转代码服务由CSDN问答提供 功能建议

我在某些代码中找到了这个:

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

[:]是什么 mean? 如果这是数组的完整切片,为什么不通过数组本身呢? 我想知道这是哪种编码风格...

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

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

    点赞 评论

相关推荐