Getting Started Flashcards
How to declare a variable in go and initialize it with a value?
var i int = 10
Can go infer types? How to declare a variable with an inferred type?
yes.
name := “Jhon Doe”
How to declare a pointer of a string? What is the default value of an empty pointer (pointer that doesn’t point to anything)?
var name *string
nil
What is de-referencing in go? How to dereference a string?
Is accessing the actual pointer content instead of the address.
*name = “Jhon Doe”
What happens if I try to dereference a pointer that was not initialized? How to fix?
It will throw the invalid memory address or nil pointer dereference error.
var name *string = new(string)
What is fmt.Println(name) output? How to output the content?
The pointer’s memory address (e.g: 0x123beef)
By dereferencing fmt.Println(*name)
What is pointer arithmetic? Does golang support that? Why?
Is manipulating the memory location fmt.Println(*(name) + 1). Golang doesn’t support that because it is too error prone.
How can I grab the address of a variable in go?
ptr := &name
What is an implicit-typed constant in go?
Is a constant value that will adjust itself to match the operation (e.g: const +1 and const + 1.2).
Should I define the value of a const in the same line of the declaration? How does it look like?
Yes. const c = 3
Can I define a type in a constant? What happens then?
Yes. The type is checked.
What is iota? When does it resets?
Is an unique-automatic-increment value that can be used in compile time. Resets in a new const() block.
Do I have to re-state iota everytime?
No. When not specified below an iota, the other consts will get iota automatically.
Can a const use the return value of a function?
no. consts can only be assigned with compile-time stuff - NOT runtime.
What replaces a class in go?
struct
What is an array in golang? How to declare one and set value?
A fixed-size and same-type list of elements.
var arr [3] int //arr := [3]int{1,2,3}
arr[0] = 1
What is a slice? Does it have a copy of the array? How to declare one
Is the full array or a part of the array. Does not contain a copy of the values (changes the sliced array).
slice = arr[:]
Can I use slice to create a non-fixes size array? How to declare one? How to add a value to the slice?
Yes.
slice := []int{1,2,3}
append(slice, 4)
How to get a slice of the array using start and end (BUT NOT INCLUDING) positions?
slice2 := slice[1:2] // read the second element only because it reads until 2 but NOT including 2