From charlesreid1

No edit summary
Line 28: Line 28:
...
...
var slice []byte = buffer[100:150]
var slice []byte = buffer[100:150]
</pre>
alternatively,
<pre>
slice := buffer[100:150]
</pre>
Think of a slice variable as a data structure with two elements: a length, and a pointer to an element of the array.
We can also take a slice of the slice:
<pre>
slice2 := slice[5:10]
</pre>
</pre>



Revision as of 06:46, 12 December 2018

Go blog post: arrays, slices, and strings: https://blog.golang.org/slices

Arrays in Go

"Arrays are not often seen in Go programs because the size of an array is part of its type, which limits its expressive power."

The most common use of arrays are to store slices, which we will see in a moment.

Array size is a part of the type

An important characteristic of arrays is that their size is a part of their type.

The two variables defined here are of two distinct types:

var buffer [256]byte
var buffer2 [512]byte

This is because the size of the array is allocated at initialization time. You can use the square bracket syntax to access elements of an array, buffer[0] through buffer[255]. The program crashes if you access an index outside of its range.

Array slices

The bracket notation with colons can be used to refer to a slice of an array. For example:

var buffer [256]byte
...
var slice []byte = buffer[100:150]

alternatively,

slice := buffer[100:150]

Think of a slice variable as a data structure with two elements: a length, and a pointer to an element of the array.

We can also take a slice of the slice:

slice2 := slice[5:10]

Flags