
Introducing Go: Build Reliable, Scalable Programs

defer is often used when resources need to be freed in some way. For example, when we open a file, we need to make sure to close it later. With defer: f, _ := os.Open(filename) defer f.Close() This has three advantages: It keeps our Close call near our Open call so it’s easier to understand. If our function had multiple return statements (perhaps
... See moreCaleb Doxsey • Introducing Go: Build Reliable, Scalable Programs
Go also provides a shorter syntax for creating arrays: x := [5]float64{ 98, 93, 77, 82, 83 }
Caleb Doxsey • Introducing Go: Build Reliable, Scalable Programs
RPC The net/rpc (remote procedure call) and net/rpc/jsonrpc packages provide an easy way to expose methods so they can be invoked over a network (rather than just in the program running them): package main import ( "fmt" "net" "net/rpc" ) type Server struct {} func (this *Server) Negate(i int64, reply *int64) error { *reply = -i return nil }
... See moreCaleb Doxsey • Introducing Go: Build Reliable, Scalable Programs
The go test command will look for any tests in any of the files in the current folder and run them. Tests are identified by starting a function with the word Test and taking one argument of type *testing.T.
Caleb Doxsey • Introducing Go: Build Reliable, Scalable Programs
The first line says this: package main This is known as a package declaration, and every Go program must start with it. Packages are Go’s way of organizing and reusing code. There are two types of Go programs: executables and libraries. Executable applications are the kinds of programs that we can run directly from the terminal (on Windows, they
... See moreCaleb Doxsey • Introducing Go: Build Reliable, Scalable Programs
In Go, if something starts with a capital letter, that means other packages (and programs) are able to see it. If we had named the function average instead of Average, our main program would not have been able to see it.
Caleb Doxsey • Introducing Go: Build Reliable, Scalable Programs
Go also has a mechanism for combining interfaces, types, variables, and functions together into a single component known as a package.
Caleb Doxsey • Introducing Go: Build Reliable, Scalable Programs
An array is a numbered sequence of elements of a single type with a fixed length. In Go, they look like this: var x [5]int x is an example of an array that is composed of five ints.
Caleb Doxsey • Introducing Go: Build Reliable, Scalable Programs
package main import "fmt" func main() { panic("PANIC") str := recover() // this will never happen fmt.Println(str) } But the call to recover will never happen in this case, because the call to panic immediately stops execution of the function. Instead, we have to pair it with defer: package main import "fmt" func main() { defer func() {
... See more