Go Cheatsheet
Go Cheatsheet
com/chap-42-cheatsheet
1 Build a program
When your main file (that belongs to package main and have a main function) has the following relative path : /my/program/main.go.
Open a terminal and type
The program will be compiled. A binary named binaryName will be created in the current directory (where you execute the command)
2 Slices
• A growable collection of elements of the same type.
• A good resource for playing with slices is the “Slice Tricks” page1
a := [4]int{1,2,3,4}
s = a[:3]
// s = [1,2]
// capacity = 4
// length = 2
get the element of slice s at index 8. (be careful, the index starts at 0)
1 of 9 02/01/2023, 02:25
Cheatsheet - Practical Go Lessons https://www.practical-go-lessons.com/chap-42-cheatsheet
2.4 Copy
• copy builtin allows copying data from (source) one slice to another (destination)
// OR
a = nil
3 Go modules
• Initialize Go modules
◦ Usually, the module path is an URL of a code-sharing website (GitHub, GitLab, bitbucket ...)
• Upgrade all dependencies to the latest version (minor versions and patches)
$ go get -u
$ go get gitlab.com/loir402/foo
$ $ go get module_path@X
Where X can be :
◦ A commit hash
▪ Ex : b822ebd
◦ A version string
▪ Ex : v1.0.3
• Cleanup your go.mod and go.sum file
$ go mod tidy
2 of 9 02/01/2023, 02:25
Cheatsheet - Practical Go Lessons https://www.practical-go-lessons.com/chap-42-cheatsheet
$ go mod graph
$ go mod vendor
• Check that the dependencies downloaded locally have not been altered
$ go mod verify
The paper and the digital edition of this book are available here. ×
I also filmed a video course to build a real world project with Go.
4 Goimports
goimports is a command-line tool to automatically sort the imports of a source file : Here is an example of unsorted import declarations
//...
import (
"encoding/csv"
"fmt"
"log"
"math/rand"
"maximilien-andile.com/errors/application/generator"
"os"
"time"
)
//...
import (
"encoding/csv"
"fmt"
"log"
"math/rand"
"os"
"time"
"maximilien-andile.com/errors/application/generator"
)
4.1 Installation
Open a terminal and type the following command :
$ go get golang.org/x/tools/cmd/goimports
To make it available everywhere, make sure to add the folder $GOPATH/bin to your PATH
4.2 Usage
The command to use is :
$ goimports -w file.go
3 of 9 02/01/2023, 02:25
Cheatsheet - Practical Go Lessons https://www.practical-go-lessons.com/chap-42-cheatsheet
5 Unit Tests
5.1 Test files
• Tests files are placed in the package directory
5.4 Commands
• Run all tests in a project
$ go test ./...
4 of 9 02/01/2023, 02:25
Cheatsheet - Practical Go Lessons https://www.practical-go-lessons.com/chap-42-cheatsheet
$ go test
$ go test modulepath/packagename
6 Naming Conventions
6.1 Module path
The module path is generally an URL pointing to a code-sharing website.
Ex : gitlab.com/loir402/bluesodium
module gitlab.com/loir402/bluesodium
go 1.15
Others will use the module path to import your module (if you have access to the repository) via, for instance, the go get command
go get gitlab.com/loir402/bluesodium
The last part of the URL should match the name of the principal package of your module (that will generally be placed at the root of the
project directory).
package main
import "gitlab.com/loir402/bluesodium"
func main() {
bluesodium.Color()
}
• simple
• concise
package builtin
//...
type error interface {
Error() string
}
5 of 9 02/01/2023, 02:25
Cheatsheet - Practical Go Lessons https://www.practical-go-lessons.com/chap-42-cheatsheet
The paper and the digital edition of this book are available here. ×
I also filmed a video course to build a real world project with Go.
8 Type assertion
Here is the syntax of a type assertion.
x.(T)
err := doSomething()
In this program, we define a function doSomething which returns an element of type interface error . We execute this function, and we
assign the return value to a new variable err .
We just know that err is of type interface error . We want to check that the dynamic type of err is *ReadingError . We can use a type
assertion :
// type assertion
v, ok := err.(*ReadingError)
if ok {
fmt.Println("err is of type *ReadingError")
}
v is of type *ReadingError
ok is equal to true2
• Otherwise
v is the zero value of the type *ReadingError . In this context, it’s equal to nil .
ok is equal to false3
6 of 9 02/01/2023, 02:25
Cheatsheet - Practical Go Lessons https://www.practical-go-lessons.com/chap-42-cheatsheet
Then we define a new type MyAdder which implements Adder and Divider .
Let’s check if the return value of foo also implements the Divider interface :
func main() {
x := foo()
if v, ok := x.(Divider); ok {
fmt.Println("x implements also interface Divider",v)
}
}
The syntax is identical. The type assertion will also check if x is not nil .
v implements Divider
ok is equal to true
• Otherwise
v is equal to nil
ok is equal to false
v, ok := x.(Divider)
your program will not panic if x is not of type Divider . Whereas the following syntax might cause a panic :
v := x.(Multiplier)
fmt.Printf("%v", v)
7 of 9 02/01/2023, 02:25
Cheatsheet - Practical Go Lessons https://www.practical-go-lessons.com/chap-42-cheatsheet
goroutine 1 [running]:
main.main()
/path/to/main.go:38 +0x100
9 Environment variables
To check if an environment variable exists, you can use the os package :
10 Useful links
• The Go developer mailing list: https://groups.google.com/g/golang-dev
1. See https://github.com/golang/go/wiki/SliceTricks↩
Bibliography
• [minimal-version-cox] Cox, Russ. 2018. “Minimal Version Selection.” https://research.swtch.com/vgo-mvs.pdf.
Previous
Design Recommendations
Table of contents
Did you spot an error ? Want to give me feedback ? Here is the feedback page! ×
Newsletter:
Like what you read ? Subscribe to the newsletter.
Practical Go Lessons
By Maximilien Andile
Copyright (c) 2023
Follow me Contents
Posts
Book
Support the author Video Tutorial
About
The author
Legal Notice
8 of 9 02/01/2023, 02:25
Cheatsheet - Practical Go Lessons https://www.practical-go-lessons.com/chap-42-cheatsheet
Feedback
Buy paper or digital copy
Terms and Conditions
9 of 9 02/01/2023, 02:25