Effective Go Flashcards
Based on the book Effective Go
How do you verify the expected output from Go Example code?
Use an output comment after the print code. e.g.
func ExampleURL() { u, err := url.Parse("http://foo.com/go") if err != nil { log.Fatal(err) } u.Scheme = "https" fmt.Println(u) // Output: // http://foo.com/go }
How is unordered expected output handled in Example code?
Where the output is in a random order you can use the following comment:
~~~
func ExamplePerm() {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
for _, v := range r.Perm(3) {
fmt.Println(v)
}
// Unordered output:
// 2
// 0
// 1
}
~~~
Give the commands that generate a coverage profile and then view it in your default browser
go test -coverprofile cover.out go tool cover -html=cover.out
How can you toggle a view of unit test coverage with the vim-go plugin
:GoCoverageToggle
<leader>c
Generate a coverage profile and save it to a file named cover.out
go test -coverageprofile cover.out
View the coverage profile from a the file cover.out
in a browser
go tool cover -html=cover.out
Show the test coverage in percentage without needing a coverage profile file
go test -cover
Give the command to run benchmarks
go test -bench .
What method can you call to report allocations in a benchmark
b.ReportAllocs()
What commands can be used to comparing benchmark results
$ go install golang.org/x/perf/cmd/benchstat@latest go test -bench . -count 10 > old.txt ...optimise code... go test -bench . -count 10 > new.txt benchstat old.txt new.txt
What command runs a benchmark test 10 times
go test -bench . -count 10
Give an example of an import statement
import "fmt"
Give and example of a factored import statement
import (
“fmt”
“math”
)
What are exported names
In Go, a name is exported if it begins with a capital letter.
When importing a package, you can refer only to its exported names.
Declare a function to add two values x and y
func add(x, y int) int { return x + y }
What is a naked return value
A return statement without arguments returns the named return values.
Naked returns should only be used in short functions.