From charlesreid1

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


=Arrays in Go=
=Basics=


"Arrays are not often seen in Go programs because the size of an array is part of its type, which limits its expressive power."
==Initialization==
 
To initialize an array, use the familiar square bracket notation.
 
<pre>
var keys []int
for k := 0; k < 10; k++ {
    keys = append(keys, k)
}
</pre>


The most common use of arrays are to store slices, which we will see in a moment.
In this way, we can think of Go's built-in array data structure as being a bit like Java's ArrayList data structure, in that it provides high-level methods that don't require the user to re-allocate space every time.


==Array size is a part of the type==
==Array size is a part of the type==


An important characteristic of arrays is that their size is a part of their type.
An important characteristic of arrays is that their size is a part of their type.
"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 two variables defined here are of two distinct types:
The two variables defined here are of two distinct types:

Revision as of 21:34, 13 December 2018

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

Basics

Initialization

To initialize an array, use the familiar square bracket notation.

var keys []int
for k := 0; k < 10; k++ {
    keys = append(keys, k)
}

In this way, we can think of Go's built-in array data structure as being a bit like Java's ArrayList data structure, in that it provides high-level methods that don't require the user to re-allocate space every time.

Array size is a part of the type

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

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

See Go/Slices

Flags