Go Basics Flashcards

1
Q

Create a map

A

m := map[string]int{}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Iterate through map

A

for k, v := range myMap { … }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Check if map contains a key

A

val, ok := myMap[key]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Absolute value function

A

import “math”
math.Abs(n)
* note that this takes and returns a float64 value

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Sort an array of ints

A

import “sort”
sort.Ints(array)
// This sort happens in place

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Create a 2D slice

A

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/

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Print the value of a variable

A

import “fmt”
fmt.Printf(“%v”, variable)
// use “%+v” to add field names to structs

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Print hello world

A

import “fmt”
fmt.Println(“hello world”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Take the square root of a number

A

import “math”
math.Sqrt(n)
* input and output is float64

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Write a function that takes 2 integers as parameters and returns 2 integers

A

func myfunction(x, y int) (int, int) { … }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Define the variable i equal to 1 outside of a function

A

var i int = 1
(the := construct is only available inside a function)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Convert the variable i of type integer into a floating number

A

f := float64(i)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Declare a constant variable

A

const Hello string = “hello”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Create a while loop

A

for x < 100 { x += 1 }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Create an infinite loop

A

for { … }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Return x to the nth power

A

import “math”
math.Pow(x, n)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Write a switch statement

A

switch name {
case “matt”:
fmt.Println(“Hello Matt!”)
case “bob”:
fmt.Println(“Hello Bob!”)
default:
fmt.Println(“hello”)
}

or

switch {
case name == “matt”:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What is a pointer?

A

It holds the memory address of a variable

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Initialize a pointer for a new variable p of type integer

A

var p *int

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Generate a pointer for the existing variable p

A

i = &p

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Create a pointer for the integer i, print it’s value through the pointer, and set i through the pointer

A

p = &i
fmt.Println(*p) // read i through the pointer p
*p = 21 // set i through the pointer p

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What is a struct?

A

A collection of fields

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Declare a variable as an array of 10 integers

A

var x [10]int
OR
x := [10]int{}
OR
x := make([]int, 10)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Add the number 1 to the end of a slice

A

s = append(s, 1)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Loop through an array
for i, v := range arr {}
26
Remove the key "k" from the map "m"
delete(m, k)
27
Check if the key "k" is present in the map "m"
elem, ok := m[k]
28
Create an add method for the type Num struct { X, Y int } and use it
func (n Num) Add() int { return n.X + n.Y } n := Num{ X: 3, Y: 4 } n.Add() The Add method has a *receiver* of type Num called n. A method is just a function with a receiver argument
29
Define a method that returns the absolute value of an integer and use it
type MyInt int func (i MyInt) Abs() int { if i < 0 { return int(-i) } return int(i) } i := MyInt(-2) i.Abs() // Return values must be converted from MyInt to Int
30
Create a method that doubles the value of an integer in place
type MyInt int func (i *MyInt) Double() { *i = *i * 2 }
31
Write a function called Scale that takes 2 parameters: (1) type Vertex Struct { X, Y float64 } and (2) a number to scale it by. The function should modify the original struct values without using a receiver. Then use the function.
func Scale (v *Vertex, f float64) { v.X = v.X * f v.Y = v.Y * f } v := Vertex{ X: 1, Y: 2 } Scale(&v, 10)
32
When should pointer receivers be used?
When (1) the method should modify the value that its receiver points to or (2) to avoid copying the value (especially if large) on each method call
33
What's the difference between pointer receivers and value receivers?
Methods with "pointer receivers" can modify the value to which the receiver points, which is more common than "value receivers". Value receivers operate on a copy of the original value, which is the same as for any other function argument. Receivers (pointers or values) conveniently take either a value or a pointer as the receiver when called, unlike functions. In other words, methods are more flexible than functions. All methods on a given type should have either value or pointer receivers, but not a mixture of both
34
What is an interface?
A collection of methods
35
Reverse a word (eg hello becomes olleh)
reverse := []byte{} for i := len(word)-1; i >= 0; i-- { reverse = append(reverse, word[i]) } OR package main import "fmt" func main () { word := []rune("hello") first := 0 last := len(word) - 1 for first < last { word[first], word[last] = word[last], word[first] first++ last-- } fmt.Println(string(word)) } * Rune is more common than Byte
36
Convert integer to string
import "strconv" strconv.Itoa(n)
37
What is a rune type?
Unicode characters
38
Convert string to rune
[]rune(myString)
39
Convert runes to string
string(myRunes)
40
What is a method?
A function with a receiver argument
41
What's the different between "func (v Vertex) MyFun() {}" and "func (v *Vertex) MyFun() {}"
The latter can modify its receiver. If there isn't a pointer receiver then the passed receiver is a copy
42
What is a byte type?
An ASCII character
43
How should each Go file start?
package main func main () { . . . }
44
How to convert string to integer?
import "strconv" n, error := strconv.ParseInt("101", 10, 64) // 10 is the base; 64 is the bytes (could also be 32)
45
How to traverse a linked list?
type LinkedList struct { Value int Next *LinkedList } currentNode := linkedList for currentNode != nil { currentNode = currentNode.Next } return linkedList
46
Round a floating number up to nearest integer
import "math" math.Ceil(n)
47
Create a breadth-first search
package main type Node struct { Name string Children []*Node } func (n *Node) BreadthFirstSearch(array []string) []string { queue := []*Node{n} for len(queue) > 0 { current := queue[0] array = append(array, current.Name) queue = queue[1:] for _, child := range current.Children { queue = append(queue, child) } } return array }
48
Create a depth-first search
type Node struct { Name string Children []*Node } func (n *Node) DepthFirstSearch(array []string) []string { array = append(array, n.Name) for _, child := range n.Children { array = child.DepthFirstSearch(array) } return array }
49
Sort a 2D array by first values (integers) in inner arrays
import "sort" sort.Slice(myArray, func(i, j ints) bool { return myArray[i][0] < myArray[j][0] })
50
Sort the following by age people := []struct { Name string Age int }{ {"Matt", 38}, {"Megan", 39}, }
import "sort" sort.Slice(people, func (i, j int) bool { return people[i].Age < people[j].Age })
51
Replace words in a string
import "strings" newStr := strings.Replace(oldString, "old", "new", -1) // the last number is how many times to make the replacement where -1 is unlimited
52
Generate a random integer from 0 to 100
import "math/rand" rand.Intn(101) // n cannot be 0
53
Cast an interface value (eg variable name `value`) to a concrete type (eg integer)
v, ok := value.(int)
54
Make an HTTP request
import "net/http" resp, err := http.Get("https://example.com") if err != nil {
55
Check if a variable (eg circle) is an instance of an interface (eg Shape) and cast it into its underlying concrete type (shape) if it is
c, ok := circle.(Shape)
56
Use a type switch statement to cast a variable to the correct type
switch v := num.(type) { case int: fmt.Printf("%T\n", v) case string: fmt.Printf("%T\n", v) default: fmt.Printf("%T\n", v) }
57
Define a Firetruck type that extends a Car type
type Car struct { make string model string } type Truck struct { Car bedSize int } truck := Truck{ Car: Car{ make: "Ford", model: "F150", }, bedSize: 8, } fmt.Println(truck.make) # An embedded struct's fields are accessed at the top level, unlike nested structs
58
Define a function with named return values
func myFunc(x int) (myReturnValue int) { ... }
59
Define more than 1 constant variable at a time
const ( planFree = "free" planPro = "pro" )
60
Define an error
import "errors" errors.New("this is an error message")
61
Write a function with an arbitrary number of final arguments and then call that function using the spread operator
func main() { names := []string{"a", "b", "c"} test(names...) } func test(a ...string) { for _, v := range a { fmt.Println(v) } }
62
Append one array (eg y) to another (eg x)
append(x, y...)
63
Add multiple items to an array
append(x, 1, 2, 3)
64
Check if an array contains a value
numbers := []int{0, 42, 10, 8} slices.Contains(numbers, 10) // true
65
Create a one-liner if statement condition that also defines a value in the if statement
if v, ok := getSomething(); ok { ... }
66