Golang Quick Reference
How to Use Collections
How to Use Slices
// Features: mutable, pass by reference, heap allocated
a := []int{1,2,3,4,5} // shorthand and initialization
// Can also specify index for placeholder
a := []int{0:1,4:3}
// Add
a = append(a, 6)
// Delete
// Index of element to delete
index := 2
// Delete element
slice = append(slice[:index], slice[index+1:]...) // This is also array merging
// Modify and read same as arrayAbout Length and Capacity in Slices
// Length (Length) refers to the number of elements currently contained in the slice.
// Capacity (Capacity) refers to the size of the underlying array, i.e., the number of elements the slice can accommodate, the upper limit.
a := make([]byte, 5, 10) // This means slice a can accommodate up to 10 byte elements, but currently only has 5 elements.
// Can omit capacity
a := make([]byte, 5)
// Syntax explanation a[b:c] =>
// b represents current index, if empty then index is 0
// c represents current index, if empty then index is len(a)
s := x[:] // slice s points to array x's memory space, changing slice s's values also affects array x's valuesHow to Iterate Slices
for k,v := range a {}
for _,v := range a {} // don't need index
for k := range a {} // only need index
for range time.Tick(time.Second) {} // need neitherHow to Use Arrays
// Features: fixed size, pass by value, stack allocated
a := [5]int{1,2,3,4,5}
// Cannot add or delete
// Modify
a[3] = 6
// Read
a[3]How to Use switch
switch a {
case "a":
// todo
case "b", "c": // matches either b or c
// todo
default:
// todo
}
// Can also prepend a statement
switch a:=1; a { ... }How to Use for Loops
for {} // equivalent to while true
for a < 19 {} // equivalent to while a < 19
for a := 10; a<99; a++ {} // normal usage
// Also supports break and continue with outer labels
here:
for i := 0; i < 2; i++ {
for j := i + 1; j < 3; j++ {
if i == 0 {
continue here
}
fmt.Println(j)
if j == 2 {
break
}
}
}
there:
for i := 0; i < 2; i++ {
for j := i + 1; j < 3; j++ {
if j == 1 {
continue
}
fmt.Println(j)
if j == 2 {
break there
}
}
}How to Use if Structure
if a > 0 {}
// Can add additional statement and end with semicolon
if a := b+c; a > 0 {}About Package and Default Constraints
Add package declaration at the very beginning of each Go source file (excluding comments)
Executable files are in main package
Convention: package name == last name of package import path (import path math/rand => package name rand)
Identifiers starting with uppercase: exported identifiers, visible to other packages
Identifiers starting with lowercase: private identifiers, not visible to other packagesHow to Declare Functions
func a() {}
func a(b int){}
func a(b, c int){} // multiple of same type
func a() string {}
// Return value
func a() (int,string){
return 1, "1"
}
// Return identifier, just return directly
func a() (b int, c string){
b = 1
c = "1"
return
}Function Passing and Closures
// Used as parameter
add := func(a,b)int{
return a+b
}
// Used as return value
func wrapAdd() (add func() int) {
c := 1
add = func() int { return c }
return
}Variadic Functions
func a(args ...int) int {
return 1
}How to Declare Variables
var a int = 1
a := 1
const a = "1"iota Tricks
-
Auto-increment enum values
const ( Red = iota // 0 Green // 1 Blue // 2 ) -
Use bit operations for flag constants
const ( FlagNone = 0 // 0 FlagA = 1 << iota // 1 FlagB = 1 << iota // 2 FlagC = 1 << iota // 4 ) -
Skip unneeded values
const ( _ = iota // skip first enum value January = 1 + iota // 1 February // 2 March // 3 )
Ways to Import Other Files
- Relative path import: Use relative paths to import other files. This method is suitable for referencing other files in the same project. For example,
import "./utils"will import theutilsfile in the current project. - Absolute path import: Use absolute paths to import other files. This method is suitable for referencing files located in different projects or libraries. For example,
import "github.com/example/package"will import files from thegithub.com/example/packagepackage. - Standard library import: Go language provides many standard libraries that can be used directly without additional imports. For example,
import "fmt"will import thefmtpackage from the standard library. - Alias import: You can set aliases for imported packages or files to use more concise names in code. For example,
import utils "github.com/example/package"will set an aliasutilsforgithub.com/example/package, and then you can useutilsto access the package’s content. - Blank identifier import: Sometimes you may just want to execute the
initfunction in a file without using other content from that file. In this case, you can use the blank identifier_for import. For example,import _ "github.com/example/package"will execute theinitfunction in thegithub.com/example/packagepackage, but won’t use other content from that package in the code. - Using dot operator import can make code more concise, but may also reduce code readability
Common CLI Commands
go build: Used to compile Go code and generate executable files. For example, go build main.go will compile the main.go file and generate an executable file.
go run: Used to compile and run Go code. For example, go run main.go will compile and directly run the main.go file.
go test: Used to run Go unit tests. Through the go test command, you can automatically run test files in the project and output test results.
go get: Used to fetch and install third-party dependency packages. For example, go get github.com/example/package will fetch and install the github.com/example/package dependency package.
go mod init: Used to initialize Go project module management. By executing the go mod init command, you can create a new go.mod file for managing project dependencies.
go mod tidy: Used to automatically clean up unused dependencies in the project. Running go mod tidy will check project dependencies and remove dependencies that are no longer needed.
go mod vendor: Used to copy project dependencies to the project's vendor directory. By running go mod vendor, you can copy all dependencies to the project for offline building and deployment.
go doc: Used to view Go code documentation. For example, go doc fmt.Println will display the documentation for the Println function in the fmt package.