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/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 JoePkgcat $GOROOT/github.com/YourName/repoName/main.go
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)get length of slice
fmt.Println(len(words))delete slice elements 2-4
z := []int{9, 8, 7, 6, 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 extraConstant
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, 64inflexible, 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)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]]delete a key
delete(age, "Joe")Pointers
show memory address of a variable
s := "abc"print string
fmt.Println("Hello, world")print value
fmt.Printf(variable)print variable and string
fmt.Printf("the answer is:", variable)get length of string
fmt.Println(len(variable))package alias
package mainimport ( mongo "/lib/mongodb/db")install dependency manager
apt install go-dep
dep init
name Go file with underscore
_test.go
open file for reading
read in a struct, generate a pretty print JSON
Logical Operators
&& = and
|| = or
! = not
sss
ss
for loop
i := 1 for i <= 3 {if / Else
if num := 9; num < 0 {Switch Case
i := 2regular 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"}