what does the symbol [:] mean in Go?

Issue

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…

Solution

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 := [4]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.

Answered By – maerics

Answer Checked By – Pedro (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.