《A Tour of Go》 Study note

Some tips I don’t know!


  • By convention, the package name is the same as the last element of the import path. For instance, the "math/rand" package comprises files that begin with the statement package rand.

  • Naked return statements should be used only in short functions. They can harm readability in longer functions.

  • Outside a function, every statement begins with a keyword (var, func, and so on) and so the := construct is not available.

  • Basic types:

    • byte // alias for uint8
    • rune // alias for int32
      // represents a Unicode code point
    • The int, uint, and uintptr types are usually 32 bits wide on 32-bit systems and 64 bits wide on 64-bit systems. When you need an integer value you should use int unless you have a specific reason to use a sized or unsigned integer type.
  • For:

    • The init and post statements are optional, like this: for ; sum < 1000; {... is correct.
  • An array’s length is part of its type, so arrays cannot be resized.

  • Slices are like references to arrays: A slice does not store any data, it just describes a section of an underlying array.

  • The make function allocates a zeroed array and returns a slice that refers to that array:

    • a := make([]int, 5)  // a len=5 cap=5 [0 0 0 0 0]
      b := make([]int, 0, 5) // b len=0 cap=5 []
      c := b[:2] // c len=2 cap=5 [0 0]
      d := c[2:5] // d len=3 cap=3 [0 0 0]
  • Range:

    • When ranging over a slice, two values are returned for each iteration. The first is the index, and the second is a copy of the element at that index.
0%