Select 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. Default Selection The default case in a select is run if no other case is ready. Use a default case to try a send or receive without blocking: 1 2 3 4 5 6 select { case i := <-c: // use i default: // receiving from c would block }
Goroutines A goroutine is a lightweight thread managed by the Go runtime. 1 go f(x, y, z) The evaluation of f, x, y, and z happens in the current goroutine and the execution of f happens in the new goroutine. Goroutines run in the same address space, so access to shared memory must be synchronized. The sync package provides useful primitives, although you won’t need them much in Go as there are other primitives.
Methods Go does not have classes. However, you can define methods on struct types. The method receiver appears in its own argument list between the func keyword and the method name. You can declare a method on any type that is declared in your package, not just struct types. You cannot define a method on a type from another package (including built in types). Methods can be associated with a named type or a pointer to a named type.
Flow control statements Go has only one looping construct, the for loop. For is Go’s “while” Like for, the if statement can start with a short statement to execute before the condition. A case body breaks automatically, unless it ends with a fallthrough statement. A defer statement defers the execution of a function until the surrounding function returns. The deferred call’s arguments are evaluated immediately, but the function call is not executed until the surrounding function returns.
Basics Every Go program is made up of packages. Programs start running in package main. factored import statement. 1 2 3 4 import ( "fmt" "math" ) In Go, a name is exported if it begins with a capital letter. Functions in Golang 1 2 3 func add(x int, y int) int { return x + y } When two or more consecutive named function parameters share a type, you can omit the type from all but the last.