From c852c887d7d4586b493fda1c60909ff2d8aa83d2 Mon Sep 17 00:00:00 2001 From: Mark McGranaghan Date: Wed, 10 Oct 2012 15:30:43 -0700 Subject: [PATCH] publish arrays --- examples.txt | 2 +- examples/arrays/arrays.go | 38 ++++++++++++++++++++++++++++++++++++-- examples/arrays/arrays.sh | 12 ++++++++++++ examples/maps/maps.go | 2 +- 4 files changed, 50 insertions(+), 4 deletions(-) create mode 100644 examples/arrays/arrays.sh diff --git a/examples.txt b/examples.txt index 61e0d79..e298737 100644 --- a/examples.txt +++ b/examples.txt @@ -6,7 +6,7 @@ Hello World # For # If/Else # Switch -# Arrays +Arrays # Slices Maps # Range diff --git a/examples/arrays/arrays.go b/examples/arrays/arrays.go index 3798840..dbde910 100644 --- a/examples/arrays/arrays.go +++ b/examples/arrays/arrays.go @@ -1,10 +1,44 @@ +// In Go, an array is a numbered sequence of elements of a +// specific length. + package main import "fmt" func main() { + + // The type of elements and length are both part of + // the array's type. Here we create an array `x` that + // will hold exactly 5 ints. var x [5]int + + // By default an array is zero-valued, which for ints + // means an array of `0`s. + fmt.Println("emp:", x) + + // We can set a value at a given index using the + // `array[index] = value` syntax, and get a value + // with `array[index]`. x[4] = 100 - fmt.Println(x) - fmt.Println(x[4]) + fmt.Println("set:", x) + fmt.Println("get:", x[4]) + + // Use this syntax to decalare and initalize an array + // in one line. + y := [5]int{1, 2, 3, 4, 4} + fmt.Println("dcl:", y) + + // The builtin `len` returns the length of an array. + fmt.Println("len:", len(x)) + + // Array types are one-dimensional, but you can + // compose types to build multi-dimensional data + // structures. + var twoD [2][3]int + for i := 0; i < 2; i++ { + for j := 0; j < 3; j++ { + twoD[i][j] = i + j + } + } + fmt.Println("2d: ", twoD) } diff --git a/examples/arrays/arrays.sh b/examples/arrays/arrays.sh new file mode 100644 index 0000000..639468f --- /dev/null +++ b/examples/arrays/arrays.sh @@ -0,0 +1,12 @@ +# Note that arrays appear in the form `[v1 v2 v3 ...]` +# when printed with `fmt.Println`. +$ go run arrays.go +emp: [0 0 0 0 0] +set: [0 0 0 0 100] +get: 100 +dcl: [1 2 3 4 4] +len: 5 +2d: [[0 1 2] [1 2 3]] + +# You'll see _slices_ much more often than arrays in +# typical Go code. We'll look at slices next. diff --git a/examples/maps/maps.go b/examples/maps/maps.go index e721141..ec30ce5 100644 --- a/examples/maps/maps.go +++ b/examples/maps/maps.go @@ -1,4 +1,4 @@ -// Maps are Go's built-in [associative data type](http://en.wikipedia.org/wiki/Associative_array) +// _Maps_ are Go's built-in [associative data type](http://en.wikipedia.org/wiki/Associative_array) // (sometimes called _hashes_ or _dicts_ in other languages). package main