Text file tour/moretypes.article

     1  More types: structs, slices, and maps.
     2  Learn how to define types based on existing ones: this lesson covers structs, arrays, slices, and maps.
     3  
     4  The Go Authors
     5  https://golang.org
     6  
     7  * Pointers
     8  
     9  Go has pointers.
    10  A pointer holds the memory address of a value.
    11  
    12  The type `*T` is a pointer to a `T` value. Its zero value is `nil`.
    13  
    14  	var p *int
    15  
    16  The `&` operator generates a pointer to its operand.
    17  
    18  	i := 42
    19  	p = &i
    20  
    21  The `*` operator denotes the pointer's underlying value.
    22  
    23  	fmt.Println(*p) // read i through the pointer p
    24  	*p = 21         // set i through the pointer p
    25  
    26  This is known as "dereferencing" or "indirecting".
    27  
    28  Unlike C, Go has no pointer arithmetic.
    29  
    30  .play moretypes/pointers.go
    31  
    32  * Structs
    33  
    34  A `struct` is a collection of fields.
    35  
    36  .play moretypes/structs.go
    37  
    38  * Struct Fields
    39  
    40  Struct fields are accessed using a dot.
    41  
    42  .play moretypes/struct-fields.go
    43  
    44  * Pointers to structs
    45  
    46  Struct fields can be accessed through a struct pointer.
    47  
    48  To access the field `X` of a struct when we have the struct pointer `p` we could
    49  write `(*p).X`.
    50  However, that notation is cumbersome, so the language permits us instead to
    51  write just `p.X`, without the explicit dereference.
    52  
    53  .play moretypes/struct-pointers.go
    54  
    55  * Struct Literals
    56  
    57  A struct literal denotes a newly allocated struct value by listing the values of its fields.
    58  
    59  You can list just a subset of fields by using the `Name:` syntax. (And the order of named fields is irrelevant.)
    60  
    61  The special prefix `&` returns a pointer to the struct value.
    62  
    63  .play moretypes/struct-literals.go
    64  
    65  
    66  * Arrays
    67  
    68  The type `[n]T` is an array of `n` values of type `T`.
    69  
    70  The expression
    71  
    72  	var a [10]int
    73  
    74  declares a variable `a` as an array of ten integers.
    75  
    76  An array's length is part of its type, so arrays cannot be resized.
    77  This seems limiting, but don't worry;
    78  Go provides a convenient way of working with arrays.
    79  
    80  .play moretypes/array.go
    81  
    82  
    83  * Slices
    84  
    85  An array has a fixed size.
    86  A slice, on the other hand, is a dynamically-sized,
    87  flexible view into the elements of an array.
    88  In practice, slices are much more common than arrays.
    89  
    90  The type `[]T` is a slice with elements of type `T`.
    91  
    92  A slice is formed by specifying two indices, a low and
    93  high bound, separated by a colon:
    94  
    95  	a[low : high]
    96  
    97  This selects a half-open range which includes the first
    98  element, but excludes the last one.
    99  
   100  The following expression creates a slice which includes
   101  elements 1 through 3 of `a`:
   102  
   103  	a[1:4]
   104  
   105  .play moretypes/slices.go
   106  
   107  
   108  * Slices are like references to arrays
   109  
   110  A slice does not store any data,
   111  it just describes a section of an underlying array.
   112  
   113  Changing the elements of a slice modifies the
   114  corresponding elements of its underlying array.
   115  
   116  Other slices that share the same underlying array will see those changes.
   117  
   118  .play moretypes/slices-pointers.go
   119  
   120  
   121  * Slice literals
   122  
   123  A slice literal is like an array literal without the length.
   124  
   125  This is an array literal:
   126  
   127  	[3]bool{true, true, false}
   128  
   129  And this creates the same array as above,
   130  then builds a slice that references it:
   131  
   132  	[]bool{true, true, false}
   133  
   134  .play moretypes/slice-literals.go
   135  
   136  
   137  * Slice defaults
   138  
   139  When slicing, you may omit the high or low bounds to use their defaults instead.
   140  
   141  The default is zero for the low bound and the length of the slice for the high bound.
   142  
   143  For the array
   144  
   145  	var a [10]int
   146  
   147  these slice expressions are equivalent:
   148  
   149  	a[0:10]
   150  	a[:10]
   151  	a[0:]
   152  	a[:]
   153  
   154  .play moretypes/slice-bounds.go
   155  
   156  
   157  * Slice length and capacity
   158  
   159  A slice has both a _length_ and a _capacity_.
   160  
   161  The length of a slice is the number of elements it contains.
   162  
   163  The capacity of a slice is the number of elements in the underlying array,
   164  counting from the first element in the slice.
   165  
   166  The length and capacity of a slice `s` can be obtained using the expressions
   167  `len(s)` and `cap(s)`.
   168  
   169  You can extend a slice's length by re-slicing it,
   170  provided it has sufficient capacity.
   171  Try changing one of the slice operations in the example program to extend it
   172  beyond its capacity and see what happens.
   173  
   174  .play moretypes/slice-len-cap.go
   175  
   176  
   177  * Nil slices
   178  
   179  The zero value of a slice is `nil`.
   180  
   181  A nil slice has a length and capacity of 0
   182  and has no underlying array.
   183  
   184  .play moretypes/nil-slices.go
   185  
   186  
   187  * Creating a slice with make
   188  
   189  Slices can be created with the built-in `make` function;
   190  this is how you create dynamically-sized arrays.
   191  
   192  The `make` function allocates a zeroed array
   193  and returns a slice that refers to that array:
   194  
   195  	a := make([]int, 5)  // len(a)=5
   196  
   197  To specify a capacity, pass a third argument to `make`:
   198  
   199  	b := make([]int, 0, 5) // len(b)=0, cap(b)=5
   200  
   201  	b = b[:cap(b)] // len(b)=5, cap(b)=5
   202  	b = b[1:]      // len(b)=4, cap(b)=4
   203  
   204  .play moretypes/making-slices.go
   205  
   206  
   207  * Slices of slices
   208  
   209  Slices can contain any type, including other slices.
   210  
   211  .play moretypes/slices-of-slice.go
   212  
   213  
   214  * Appending to a slice
   215  
   216  It is common to append new elements to a slice, and so Go provides a built-in
   217  `append` function. The [[/pkg/builtin/#append][documentation]]
   218  of the built-in package describes `append`.
   219  
   220  	func append(s []T, vs ...T) []T
   221  
   222  The first parameter `s` of `append` is a slice of type `T`, and the rest are
   223  `T` values to append to the slice.
   224  
   225  The resulting value of `append` is a slice containing all the elements of the
   226  original slice plus the provided values.
   227  
   228  If the backing array of `s` is too small to fit all the given values a bigger
   229  array will be allocated. The returned slice will point to the newly allocated
   230  array.
   231  
   232  (To learn more about slices, read the [[/blog/go-slices-usage-and-internals][Slices: usage and internals]] article.)
   233  
   234  .play moretypes/append.go
   235  
   236  
   237  * Range
   238  
   239  The `range` form of the `for` loop iterates over a slice or map.
   240  
   241  When ranging over a slice, two values are returned for each iteration.
   242  The first is the index, and the second is a copy of the element at that index.
   243  
   244  .play moretypes/range.go
   245  
   246  * Range continued
   247  
   248  You can skip the index or value by assigning to `_`.
   249  
   250      for i, _ := range pow
   251      for _, value := range pow
   252  
   253  If you only want the index, you can omit the second variable.
   254  
   255      for i := range pow
   256  
   257  .play moretypes/range-continued.go
   258  
   259  * Exercise: Slices
   260  
   261  Implement `Pic`. It should return a slice of length `dy`, each element of which is a slice of `dx` 8-bit unsigned integers. When you run the program, it will display your picture, interpreting the integers as grayscale (well, bluescale) values.
   262  
   263  The choice of image is up to you. Interesting functions include `(x+y)/2`, `x*y`, and `x^y`.
   264  
   265  (You need to use a loop to allocate each `[]uint8` inside the `[][]uint8`.)
   266  
   267  (Use `uint8(intValue)` to convert between types.)
   268  
   269  .play moretypes/exercise-slices.go
   270  
   271  * Maps
   272  
   273  A map maps keys to values.
   274  
   275  The zero value of a map is `nil`.
   276  A `nil` map has no keys, nor can keys be added.
   277  
   278  The `make` function returns a map of the given type,
   279  initialized and ready for use.
   280  
   281  .play moretypes/maps.go
   282  
   283  * Map literals
   284  
   285  Map literals are like struct literals, but the keys are required.
   286  
   287  .play moretypes/map-literals.go
   288  
   289  * Map literals continued
   290  
   291  If the top-level type is just a type name, you can omit it from the elements of the literal.
   292  
   293  .play moretypes/map-literals-continued.go
   294  
   295  * Mutating Maps
   296  
   297  Insert or update an element in map `m`:
   298  
   299  	m[key] = elem
   300  
   301  Retrieve an element:
   302  
   303  	elem = m[key]
   304  
   305  Delete an element:
   306  
   307  	delete(m, key)
   308  
   309  Test that a key is present with a two-value assignment:
   310  
   311  	elem, ok = m[key]
   312  
   313  If `key` is in `m`, `ok` is `true`. If not, `ok` is `false`.
   314  
   315  If `key` is not in the map, then `elem` is the zero value for the map's element type.
   316  
   317  *Note:* If `elem` or `ok` have not yet been declared you could use a short declaration form:
   318  
   319  	elem, ok := m[key]
   320  
   321  .play moretypes/mutating-maps.go
   322  
   323  * Exercise: Maps
   324  
   325  Implement `WordCount`.  It should return a map of the counts of each “word” in the string `s`. The `wc.Test` function runs a test suite against the provided function and prints success or failure.
   326  
   327  You might find [[/pkg/strings/#Fields][strings.Fields]] helpful.
   328  
   329  .play moretypes/exercise-maps.go
   330  
   331  * Function values
   332  
   333  Functions are values too. They can be passed around just like other values.
   334  
   335  Function values may be used as function arguments and return values.
   336  
   337  .play moretypes/function-values.go
   338  
   339  * Function closures
   340  
   341  Go functions may be closures. A closure is a function value that references variables from outside its body. The function may access and assign to the referenced variables; in this sense the function is "bound" to the variables.
   342  
   343  For example, the `adder` function returns a closure. Each closure is bound to its own `sum` variable.
   344  
   345  .play moretypes/function-closures.go
   346  
   347  * Exercise: Fibonacci closure
   348  
   349  Let's have some fun with functions.
   350  
   351  Implement a `fibonacci` function that returns a function (a closure) that
   352  returns successive [[https://en.wikipedia.org/wiki/Fibonacci_number][fibonacci numbers]]
   353  (0, 1, 1, 2, 3, 5, ...).
   354  
   355  .play moretypes/exercise-fibonacci-closure.go
   356  
   357  * Congratulations!
   358  
   359  You finished this lesson!
   360  
   361  You can go back to the list of [[/tour/list][modules]] to find what to learn next, or continue with the [[javascript:click('.next-page')][next lesson]].
   362  

View as plain text