Go Basics Flashcards
Create a map
m := map[string]int{}
Iterate through map
for k, v := range myMap { … }
Check if map contains a key
val, ok := myMap[key]
Absolute value function
import “math”
math.Abs(n)
* note that this takes and returns a float64 value
Sort an array of ints
import “sort”
sort.Ints(array)
// This sort happens in place
Create a 2D slice
mySlice := make([][]int, outerArrayLength)
mySlice[i] := make([]int, innerArrayLength)
// slices can only be 1D so you must define size of inner arrays
// you define the array from the outside-in since you can have multiple dimensions
https://golangbyexample.com/two-dimensional-array-slice-golang/
Print the value of a variable
import “fmt”
fmt.Printf(“%v”, variable)
// use “%+v” to add field names to structs
Print hello world
import “fmt”
fmt.Println(“hello world”)
Take the square root of a number
import “math”
math.Sqrt(n)
* input and output is float64
Write a function that takes 2 integers as parameters and returns 2 integers
func myfunction(x, y int) (int, int) { … }
Define the variable i equal to 1 outside of a function
var i int = 1
(the := construct is only available inside a function)
Convert the variable i of type integer into a floating number
f := float64(i)
Declare a constant variable
const Hello string = “hello”
Create a while loop
for x < 100 { x += 1 }
Create an infinite loop
for { … }
Return x to the nth power
import “math”
math.Pow(x, n)
Write a switch statement
switch name {
case “matt”:
fmt.Println(“Hello Matt!”)
case “bob”:
fmt.Println(“Hello Bob!”)
default:
fmt.Println(“hello”)
}
or
switch {
case name == “matt”:
…
What is a pointer?
It holds the memory address of a variable
Initialize a pointer for a new variable p of type integer
var p *int
Generate a pointer for the existing variable p
i = &p
Create a pointer for the integer i, print it’s value through the pointer, and set i through the pointer
p = &i
fmt.Println(*p) // read i through the pointer p
*p = 21 // set i through the pointer p
What is a struct?
A collection of fields
Declare a variable as an array of 10 integers
var x [10]int
OR
x := [10]int{}
OR
x := make([]int, 10)
Add the number 1 to the end of a slice
s = append(s, 1)
Loop through an array
for i, v := range arr {}
Remove the key “k” from the map “m”
delete(m, k)