Golang Cheat Sheet
Compile and Format
Format source code for proper syntax
go fmt src/code.goRun a go program w/o compiling
go run src/code.gogenerate a binary (will be placed in $GOPATH/bin)
cd src/project/go install
run Golang documenation in your browser
go doc -http=:8080open up browser, localhost:8080
Packages
example importing packages and using variables from each
cat $GOROOT/github.com/Joe/repoName/joe.go
package JoePkgvar MyName = "Joe"
var MyAge = 33
cat $GOROOT/github.com/YourName/repoName/main.go
package mainimport ( "fmt" "github.com/Joe/repoName/")func main() { fmt.Println(JoePkg.myName) fmt.Println(JoePkg.myAge)}
Slice (Dynamic Array)
like an array but can change size
s := []int{1,2,3}
>> [ 1 2 3 ]
append to slice
fmt.Println(append(s, 20, 21))
>> [ 1 2 3 20 21 ]
create empty slice of 3 elements
words := make([]string, 3)words[0] = "hello"
words[1] = "there"
cars := []string{"buick", "honda", "chevy"}
get length of slice
fmt.Println(len(words))append to slicewords = append(words, "sugar")
delete slice elements 2-4
z := []int{9, 8, 7, 6, 5, 3, 2, 1, 0}fmt.Println(z)
>> [9 8 7 6 5 3 2 1 0]
z = append(z[:2], z[4:]...)
fmt.Println(z)>> [9 8 5 3 2 1 0]
copy contents from 1 slice to another
s1 := []int{1,2,3} >> creates a slice of integers [1 2 3]s2 := make([]int, 2) >> creates empty slice of 2 integers [0 0]copy s1 > s2
copy(s2, s1)fmt.Println(s2) >>> [1 2] // will cut off any extraData Types
Constant
value never changes, can be number, bool, or string
const s string = "banana"get type of data structure
Types
int8 (-128 to 127)int16 (-32,768 to 32,767)int32 (2,147,483,648 to 2,147,483,647)int64 (-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807)uint8, 16, 32, 64float 32, 64Structs (similar to Class)
type person struct { name string age int}func main() { fmt.Println(person{"bob", 20}) ## {bob, 20} s := person{"joe",35} fmt.Println(s.name) ## joe}
Array
inflexible, can only declare an array size, but cant change size later
var a [5]intb := [5]int{1, 2, 3, 4, 5}fmt.Println("array is:", b)Double array (matrix)
array := [# items][max size of each array]<type>{ {array}, {array}}array := [2][4]int{{1,2,3,4}, {5,6,7}}
if Array is specified with size, and is provided w smaller size, Go will populate with zeros
array := [3][5]int{{1,2,3,4}, {5,6,7}}fmt.Println(array)>> [[1 2 3 4 0] [5 6 7 0 0] [0 0 0 0 0]]Hashes / Dictionary (Map)
package mainimport "fmt"func main() { prices := make(map[string]float64) prices["OCKOPROG"] = 89.99 prices["ALBOÖMME"] = 129.99 prices["TRAALLÅ"] = 49.99 for key, value := range prices { fmt.Printf("Key: %s\tValue: %v\n", key, value) }}Map - ie Dictionary or Hash
age := make(map[string]int)age["Joe"] = 28age["Sarah"] = 32
delete a key
delete(age, "Joe")Pointers
show memory address of a variable
s := "abc"fmt.Println(&s)0xc0000a0220
Strings
print string
fmt.Println("Hello, world")print value
fmt.Printf(variable)print variable and string
fmt.Printf("the answer is:", variable)fmt.Printf("%s\n", a)
get length of string
fmt.Println(len(variable))package alias
package mainimport ( mongo "/lib/mongodb/db")func main() { mongo.Get()
install dependency manager
apt install go-dep
dep init
TESTING
name Go file with underscore
_test.go
FILE HANDLING
open file for reading
file, err := os.Create("/tmp/file")if err != nil { panic(err)}fmt.Fprintln(file, number)
JSON
read in a struct, generate a pretty print JSON
import ( "encoding/json" "fmt" "net" "os")
type OperatingSystem struct { Kernel string `json:"kernel"` KernelRelease string `json:"kernel release"` KernelVersion string `json:"kernel version"` LSBRelease string `json:"lsb release,omitempty"`}
func main() { ret := OperatingSystem{ Kernel: "linux", KernelRelease: "123", KernelVersion: "6.3", LSBRelease: "linux mint",}
data, _ := json.MarshalIndent(ret, "", " ")fmt.Println(string(data))
Logical Operators
&& = and
|| = or
! = not
sss
ss
Conditionals
for loop
i := 1 for i <= 3 {fmt.Println(i)
i = i + 1
}
for j := 7; j <= 9; j++ {
fmt.Println(j)
}
for { fmt.Println("loop")
break
}
if / Else
if num := 9; num < 0 {fmt.Println(num, "is negative")
} else if num < 10 {
fmt.Println(num, "has 1 digit")
} else {
fmt.Println(num, "has multiple digits")
}
Switch Case
i := 2fmt.Print("write ", i, " as ")
switch i {
case 1: fmt.Println("one")
case 2: fmt.Println("two"
case 3: fmt.Println("three")
}
Functions
regular func
func NAME(incoming_var TYPE) return_var TYPE { return var}func add(a, b int) int { return a + b} func main () { result := add(1, 2) fmt.Println("1+2 =", result)} ## 1+2 = 3multiple-value return function
func SumAndProduct(A, B int) (added, multiplied int) { added = A+B multiplied = A*B return added, multiplied}Goto
func myFunc() { i := 0 Here: // label ends with ":" fmt.Println(i) i++ goto Here //jump to label "Here"}