publish arrays

This commit is contained in:
Mark McGranaghan 2012-10-10 15:30:43 -07:00
parent 031797c22f
commit c852c887d7
4 changed files with 50 additions and 4 deletions

View File

@ -6,7 +6,7 @@ Hello World
# For
# If/Else
# Switch
# Arrays
Arrays
# Slices
Maps
# Range

View File

@ -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)
}

12
examples/arrays/arrays.sh Normal file
View File

@ -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.

View File

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