Skip to content

Instantly share code, notes, and snippets.

@NorbertFenk
Created January 9, 2020 11:22
Show Gist options
  • Save NorbertFenk/ca3752f6e5dcd811e43f063e14c12f5e to your computer and use it in GitHub Desktop.
Save NorbertFenk/ca3752f6e5dcd811e43f063e14c12f5e to your computer and use it in GitHub Desktop.
Go notes through the learning phase

Arrays

  • An array type definition specifies a length and an element type.
  • For example, the type [4]int represents an array of four integers.
  • An array's size is fixed
  • Arrays can be indexed in the usual way, so the expression s[n] accesses the nth element, starting from zero.
  • Arrays do not need to be initialized explicitly; the zero value of an array is a ready-to-use
  • An array variable denotes the entire array; it is not a pointer to the first array element (as would be the case in C).
  • When you assign or pass around an array value you will make a copy of its contents.

An array literal can be specified like so: b := [2]string{"Penn", "Teller"} Or, you can have the compiler count the array elements for you: b := [...]string{"Penn", "Teller"} In both cases, the type of b is [2]string.

Slices

  • They build on arrays to provide great power and convenience.
  • The type specification for a slice is []T.
  • A slice type has no specified length.
  • Declaration: letters := []string{"a", "b", "c", "d"}
  • A slice can be created with the built-in function called make
  • make function takes a type, a length, and an optional capacity
var s []byte
s = make([]byte, 5, 5)
// s == []byte{0, 0, 0, 0, 0}
  • When the capacity argument is omitted, it defaults to the specified length.
  • The zero value of a slice is nil. The len and cap functions will both return 0 for a nil slice.
  • A slice can also be formed by "slicing" an existing slice or array.
  • Slicing is done by specifying a half-open range with two indices separated by a colon.
  • The expression b[1:4] creates a slice including elements 1 through 3 of b (the indices of the resulting slice will be 0 through 2).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment