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
Q

Loop through an array

A

for i, v := range arr {}

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

Remove the key “k” from the map “m”

A

delete(m, k)

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

Check if the key “k” is present in the map “m”

A

elem, ok := m[k]

28
Q

Create an add method for the type Num struct { X, Y int } and use it

A

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
Q

Define a method that returns the absolute value of an integer and use it

A

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
Q

Create a method that doubles the value of an integer in place

A

type MyInt int
func (i *MyInt) Double() {
*i = *i * 2
}

31
Q

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.

A

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
Q

When should pointer receivers be used?

A

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
Q

What’s the difference between pointer receivers and value receivers?

A

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
Q

What is an interface?

A

A collection of methods

35
Q

Reverse a word (eg hello becomes olleh)

A

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
Q

Convert integer to string

A

import “strconv”
strconv.Itoa(n)

37
Q

What is a rune type?

A

Unicode characters

38
Q

Convert string to rune

A

[]rune(myString)

39
Q

Convert runes to string

A

string(myRunes)

40
Q

What is a method?

A

A function with a receiver argument

41
Q

What’s the different between “func (v Vertex) MyFun() {}” and “func (v *Vertex) MyFun() {}”

A

The latter can modify its receiver. If there isn’t a pointer receiver then the passed receiver is a copy

42
Q

What is a byte type?

A

An ASCII character

43
Q

How should each Go file start?

A

package main

func main () {
. . .
}

44
Q

How to convert string to integer?

A

import “strconv”
n, error := strconv.ParseInt(“101”, 10, 64)

// 10 is the base; 64 is the bytes (could also be 32)

45
Q

How to traverse a linked list?

A

type LinkedList struct {
Value int
Next *LinkedList
}

currentNode := linkedList
for currentNode != nil {
currentNode = currentNode.Next
}
return linkedList

46
Q

Round a floating number up to nearest integer

A

import “math”
math.Ceil(n)

47
Q

Create a breadth-first search

A

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
Q

Create a depth-first search

A

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
Q

Sort a 2D array by first values (integers) in inner arrays

A

import “sort”

sort.Slice(myArray, func(i, j ints) bool {
return myArray[i][0] < myArray[j][0]
})

50
Q

Sort the following by age
people := []struct {
Name string
Age int
}{
{“Matt”, 38},
{“Megan”, 39},
}

A

import “sort”
sort.Slice(people, func (i, j int) bool {
return people[i].Age < people[j].Age
})

51
Q

Replace words in a string

A

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
Q

Generate a random integer from 0 to 100

A

import “math/rand”
rand.Intn(101)
// n cannot be 0

53
Q

Cast an interface value (eg variable name value) to a concrete type (eg integer)

A

v, ok := value.(int)

54
Q

Make an HTTP request

A

import “net/http”
resp, err := http.Get(“https://example.com”)
if err != nil {

55
Q

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

A

c, ok := circle.(Shape)

56
Q

Use a type switch statement to cast a variable to the correct type

A

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
Q

Define a Firetruck type that extends a Car type

A

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
Q

Define a function with named return values

A

func myFunc(x int) (myReturnValue int) { … }

59
Q

Define more than 1 constant variable at a time

A

const (
planFree = “free”
planPro = “pro”
)

60
Q

Define an error

A

import “errors”
errors.New(“this is an error message”)

61
Q

Write a function with an arbitrary number of final arguments and then call that function using the spread operator

A

func main() {
names := []string{“a”, “b”, “c”}
test(names…)
}

func test(a …string) {
for _, v := range a {
fmt.Println(v)
}
}

62
Q

Append one array (eg y) to another (eg x)

A

append(x, y…)

63
Q

Add multiple items to an array

A

append(x, 1, 2, 3)

64
Q

Check if an array contains a value

A

numbers := []int{0, 42, 10, 8}
slices.Contains(numbers, 10) // true

65
Q

Create a one-liner if statement condition that also defines a value in the if statement

A

if v, ok := getSomething(); ok { … }

66
Q
A