Golang

Language

  • Unused imports and variables cause compiler error.

  • Inside a function, the := short assignment statement can be used in place of a var declaration with implicit type.

  • Constants cannot be declared using the := syntax.

  • switch

    • No break statement needed at the end of each case
    • case can have boolean expression instead of a literal value, similar to if-else structure
  • for

    • Using range to iterate array
  • new and make

    • make returns an initialized (not zeroed) value of type T.
    • make applies only to maps, slices and channels and does not return a pointer.

Function

  • No overloading
defer
  • Similar to Java's finally block, but unstructured, and can be used for a simple method call or a closure, and doesn't have to be at the end of the method.

Array & Slice

  • When you pass variables between functions, they’re always passed by value, and this means the entire array, regardless of its size, is copied and passed to the function.
  • Slice's length cannot exceed its capacity.
  • If you specify a value inside the [ ] operator, you’re creating an array. If you don’t specify a value, you’re creating a slice.

Concurrency

sync.Waitgroup

sync.Once

sync.Mutex & sync.RWMutex

  • Similar to Java's

    • java.util.concurrent.locks.ReentrantLock
    • java.util.concurrent.locks.ReentrantReadWriteLock
  • But mutexes in Go aren’t reentrant. If a goroutine tries to acquire the same lock twice, it deadlocks, waiting for itself to release the lock.

  • Like sync.WaitGroup and sync.Once, mutexs must never be copied. If they are passed to a function or accessed as a field on a struct, it must be via a pointer. If a mutex is copied, its lock won’t be shared.

Goroutine

  • If main function ends, all goroutines will be terminated too.

  • select statement

    • The select statement lets a goroutine wait on multiple communication operations.

    • A select blocks until one of its cases can run, then it executes that case. It chooses one at random if multiple are ready.

    • To avoid unexpected blocking, a default case should be supplied.

Channel

  • Use Channel for synchronous data exchange between goroutines, similar to a Java BlockingQueue
  • Buffered Channel can be used to implement a Semaphore control for concurrency

Engineering

Go Modules

  • Both go.mod and go.sum should be checked into version control.
List all dependencies of the current module
  • go list -m all

Workspace && Version Control

  • GOPATH should point to a directory where all golang project reside.
GOPATH/
  bin/                        # Build artifacts
      hello                   # command executable
      outyet                  # command executable
  src/
      golang.org/x/example/   # Project 1 (Git repo 1)
      golang.org/x/image/     # Project 2 (Git repo 2)

References