Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Preview
Start a free Courses trial
to watch this video
So far we've only had to store single values. But it's much more common in computing to need to store an entire list of values, like items on a grocery list or phone numbers in a contact list. Go has a couple different structures that can do this: arrays, and slices. Slices are used more commonly than arrays, for reasons we'll discuss shortly, but since slices are built on top of arrays, it's important to understand arrays as well. So we'll look at arrays first.
- Array: A list of elements
- Array type is written
[n]T
, where n is the array size and T is the type of the array's elements - All elements must be of same type
- Assign/access individual elements with
a[0]
,a[1]
, etc.
package main
import "fmt"
func main() {
var months [3]string
months[0] = "Apr"
months[1] = "May"
months[2] = "Jun"
var salesByMonth [3]float64
salesByMonth[0] = 1710.26
salesByMonth[1] = 2245.97
salesByMonth[2] = 3032.40
fmt.Println(months[0], salesByMonth[0])
fmt.Println(months[1], salesByMonth[1])
fmt.Println(months[2], salesByMonth[2])
}
- Array literals using curly braces
package main
import "fmt"
func main() {
months := [3]string{"Apr", "May", "Jun"}
salesByMonth := [3]float64{1710.26, 2245.97, 3032.40}
fmt.Println(months[0], salesByMonth[0])
fmt.Println(months[1], salesByMonth[1])
fmt.Println(months[2], salesByMonth[2])
}
- Get length with
len(a)
for i := 0; i < len(months); i++ {
fmt.Println(months[i], salesByMonth[i])
}
- The init/condition/post form of
for
loop is pretty brittle. Suppose we had accidentally changed the condition toi <= len(months)
? -
for ... = range
is better.- This is essentially equivalent to "for each" in other languages.
for i, month := range months {
fmt.Println(month, salesByMonth[i])
}
- If you're not going to use the index or the value, you can provide the blank identifier instead of a variable:
for _, month := range months {
fmt.Println(month)
}
- Arrays are fixed-length; can't grow or shrink
So far,
we've only had to store single values, but
0:00
it's much more common in computing to
need to store an entire list of values,
0:02
like items on a grocery list or
phone numbers in a contact list.
0:06
Go has a couple different structures
that can do this, arrays and slices.
0:10
Slices are used more commonly than arrays,
for reasons we'll discuss shortly.
0:15
But since slices are built
on top of arrays,
0:18
it's important to
understand arrays as well.
0:21
So we'll look at arrays first.
0:23
An array consists of a list of elements.
0:25
An array type is written with
a number here in square brackets,
0:27
followed by the type name.
0:31
The number represents
the size of the array, and
0:33
the type is the type of elements
that the array will hold.
0:36
All of the elements in an array
need to be of the same type.
0:39
So for example, you can't assign
a number to this array of strings.
0:41
You can assign to an element
of an array by including
0:45
the variable that holds the array,
followed by
0:49
square brackets with the numeric index
of the element you want to assign to.
0:53
0 is the first element,
1 is the second element, and so forth.
0:58
You can assign to the element
using the equal sign,
1:02
just like you would with
any other variable.
1:04
And you can access the value that
you've stored in that element,
1:07
just by putting the variable
name that holds the array,
1:10
followed by the square brackets
with the element index.
1:14
So for example,
we assign the strings April, May, and
1:17
June to the months array here.
1:21
And then we print them out down here
one at a time, April, May, and June.
1:23
You can see that in the output
down here at the bottom.
1:29
Same thing for the sales by month,
we assign float64 values to the first,
1:32
second, and
third elements of the salesByMonth array.
1:38
And then we print them out one at
a time down here at the bottom.
1:42
If you know what the contents of
an array are going to be beforehand,
1:47
you may find it's more convenient to
populate it using an array literal.
1:50
You do that by putting the values
the array is going to hold
1:53
here in curly braces,
following the array declaration.
1:56
So this code here has the exact same
code as the lengthy previous code.
2:00
It assigns the values April, May,
and June to the array months and
2:04
then several float64 values
to the salesByMonth array.
2:09
You can get the length of an array
by using the built in len function,
2:13
short for length.
2:18
So, we could use a single print line
statement within a loop to print out
2:19
the the entire contents of the months and
2:24
salesByMonth array if we just get its
length using the length functions.
2:26
So, let's create a for loop.
2:31
We'll set up an i index variable to keep
track of where we are within the array.
2:33
We'll start that at the index 0,
and we'll continue looping while
2:39
the value in i is less than
the length of the months array.
2:43
For our post statement,
we'll just increment the index variable.
2:49
And then we'll just include
a single fmt.Println statement,
2:54
which prints the value from
months at the current index and
2:59
the value from salesByMonth
at the current index.
3:04
Save that, run it, and
we get the same result.
3:08
The form of the for
3:16
loop with the init condition and
post statement is pretty brittle though.
3:17
Suppose we'd accidentally changed
the condition to i is less than or
3:21
equal to the length of months.
3:26
Well, the length of the months array is 3,
but if we try and
3:27
use an index of 3,
that's out of bounds for the array.
3:31
Let's try running it like this.
3:35
And you see we get an error, saying
that the index we tried is out of range.
3:37
This is why Go offers another form of for
loop.
3:41
We can declare i and month variables and
3:45
say that they'll be receiving
values from range months.
3:48
We provide the name of an array here,
use the range keyword, and
3:53
we specify the names of variables
that will be receiving the current
3:57
index of the current value and
the value itself.
4:01
This will loop over the array,
assigning the index and the value for
4:05
each value the array contains.
4:09
So down here in the Println statement,
we can, instead of saying months,
4:12
at the current index, we can just
put the month variable's value.
4:16
And then we can continue to access the
salesByMonth array at the current index,
4:20
since those values correspond
to the month names.
4:27
Save this and try running it.
4:33
And you see that we get
the same output as before.
4:36
You'll find this form is
generally much safer and
4:38
less error prone than using indexes
to loop over the values in an array.
4:40
If you don't need either the index or
the value,
4:45
you can omit them using
the blank identifier.
4:47
So for example, if we didn't
need to print the salesByMonth,
4:50
we could just omit the index by
using the blank identifier there.
4:53
Whoops, slight mistake there.
5:01
Because now I'm not using
the salesByMonth array at all.
5:03
I can just comment that out,
and it should compile.
5:07
There we go, and we have just the names
of the months now, April, May, and June.
5:11
The length of arrays is fixed.
5:16
They can't grow or shrink.
5:18
For example, if we were to try to add
a fourth string to the months array,
5:19
let's say months index 3 = July.
5:24
Try saving that and running it.
5:30
We get invalid array index 3 (out
of bounds for 3-element array).
5:33
This limitation is the main reason arrays
are rarely used directly in Go programs.
5:38
It's often important to be able to add new
values onto a list after its creation.
5:43
This is why Go provides an easy to
use alternative to arrays, slices.
5:47
You need to sign up for Treehouse in order to download course files.
Sign up