Golang Flashcards
What data types exist in Golang?
In Golang we have few different data types, which are:
- integer
- float
- boolean
- byte
- string
- array and slice
- structure
- map
- interface
- rune
What is difference between:
- type Example = int
- type Example int
The difference is that in first case we create type synonym, what means that it is completely equal to original type itself, and can be freely used instead of it with full compatibility
In second case you create new type based on original type. This is separate type and can’t be used instead of original one without explicit typecasting, but you can add custom methods to this new type.
And this limitation, that you can’t freely operate two different.
What is the difference between regular functions and anonymous functions
The main difference is that anonymous functions are closures. In other words, they can freely access variables from environment where they were created.
Second big difference is that using anonymous functions you can create Immediately Invoked Function Expressions.
What is difference between errors in Golang and exceptions in other languages?
Exceptions in other languages is something what you didn’t expect to happen and they are just ignored by default.
But in Golang, errors are quite transparent, the language itself makes you understand possible problems at the moment when you write code, and do something to predict program behavior in bad case and handle this error.
What is difference between type conversion and type assertion in Golang?
The difference between type conversion int(exampleValue) and type assertion exampleValue.(int) is that in first case we transform value of one type into value of another type.
In second case we tell the compiler, that this variable type is equal to that type we assert to.
When do we need to use function “new” in Golang?
I would say, we can use new keyword everywhere where we could need to create a pointer to a value of certain type without explicit initialization
If we just try to write something like: var p *float64 = &3.5 (var p asterisk float64 equals ampersand 3 dot five) then we will get error, because in Golang primitives are provided by value and they don’t have address that you can copy and then use
There are two ways to do this.
In first case, you create separate variable first like var value = 3.5 and then on next row you write var p = &value
Second way, on first row you write var p = new(float64) and on next row you write *p = 3.5
What “defer” is used for in Golang?
Defer is a statement that you can use to execute code that goes after defer after function execution is completed. And by function completion here I mean not only that all function code was successfully executed, but also include early return and panic cases.
Defer is usually used to close streams or recover from panic. Also, you can use few defer statements in same function. This case first will be executed last called defer statement.
Finally, there are two cases when deferred code won’t be executed. These are cases when function work was finished through calling os.Exit() or log.Fatal() functions.
What is mutex?
What is difference between sync.Mutex and sync.RWMutex?
Mutex is a structure that allows to control access to certain parts of code from multiple goroutines.
Using mutex is neccessary in order to avoid race condition, when few different goroutines are trying to access same variable, for example.
The difference between Mutex and RWMutex is that Mutex always guarantee serial access to protected source, but RWMutex allow parallel access for reading.
What is pprof?
As far as I know, this is Golang profiling tool. It can be used to build charts and graphs, showing function calls and how long it takes for each of them.
It can be also used to test HTTP API endpoints performance.
What types in Golang are incomparable?
- Slices and maps, except of nil comparison
- Functions
- Other structures, containing any of listed above
In what cases the following code will fail with error?
a := map[B]int{}
a[d] = 0
e, ok := a[d]
- If B or d is not defined
- If B is not type
- a is already defined above
- Race condition because of concurrent map writing
- Type of d is not B
Is that possible to avoid race condition when multiple goroutines are trying to write into same resource without use of mutex or other synchronization mechanisms?
Yes, if GOMAXPROCS will be set to 1.
What’s a typical use case for anonymous functions?
Callbacks, goroutines creation and immediately invoked function expressions.
What is interface in Golang? How it works?
Interface in golang is an abstraction that describes set of methods that certain type must implement. If certain type implements these methods, then it implements interface too.
Golang is different from most of modern languages. In them you have to explicitly declare that this or that class or type implements this interface. In Golang works the opposite mechanism - if certain type has all required methods, it implicitly implements this or that interface.
What is difference between goroutines and threads?
The difference is in their basis, in what they are and how they work with system resoruces.
Goroutines are lightweight, they are administrated and schelduled by golang runtime in userspace.
Goroutines have some restrictions, for example, they don’t have direct access to system resources, but these limitation make them faster, more effective and effective, and again, more lightweight than regular system threads. Their minimal stack size is like two kilobytes, but it can grow up to one gigabyte if neccessary. Also, because of this lighweightness, you can create almost infinite number of goroutines while you have enough memory. You can have thousands of them.
From the other side, threads are managed by system itself in kernel space. As far as I know, these threads have much more possibilities in system interaction than goroutines, and much larger stack, what, from other side, can’t grow the same way like goroutines can do.
The main problem of threads is that they are heavy and switching between them require full context change, which is quite heavy operation too. So, you can’t create thousands of threads like you can do with goroutines.
Also, if to talk about threads, then their behavior and details can differ from one system to another, what can affect program execution. Goroutines, same time, provide more stable and predictable environment.
What are channels in Golang?
Channels are a mechanism of interaction and data transfer between goroutines.
There are two types of channels - with buffer and without.
Channels without buffer will force two goroutines to synchronize together when sending or reading something using it, because it has no inner data storage it any value put into it must be handled at same moment of time.
Channels with buffer work like a queue, and until they are overflown, you can handle information sent through them asynchronously.
What is an empty interface in Golang?
Empty interface is an interface with no declared methods in its body. Empty interface means “any type”, and if you used empty interface as function parameter type, for example, then that means that you can provide anything as function argument. This can be useful when you want to work with different types, but by some reason don’t want or can’t use generics, or in case if you simply don’t know exact type of value, for example, when you work with JSON with unknown structure.
But if we dive a bit deeper under this high-level of abstraction that I just explained, then the reason why empty interface can be used to declare variable or parameter as any type, is because of interface realization in Golang…
[Начинаю рассказывать про интерфейсы]
How does Golang garbage collector work?
Golang garbage collector work consist of two phases.
During first phase it goes through all objects from the root level recursively, and then marks all objects that it can access through references as alive.
During second phase it deletes all objects, that are not alive.
Golang garbage collector works in parallel to main go program, and prevent program from being entirely paused by it.
How does capacity changes when you append elements into slice?
Up to 1024 it doubles each time there is not enough space in slice to add new elements.
After 1024 - by 25%
Explain how to convert string to number and number to string in Go
Using Itoa and Atoi function from strconv package
How strings work in golang internally?
In Golang, strings are non-changeable arrays of bytes.
UTF-8 is used as standart encoding.
What is the difference between slices and arrays?
Array is a structure of fixed size, used to store sequence of elements, and what is provided by value.
Slice is a structure provided by reference, that doesn’t store any data itself, but instead uses certain array to store data, and slice itself is just kind of window to this array. Also, slices size can be dynamically changed.
How does map work in Go?
Map is a structure, that uses hashtable to store values by their keys.
It has inbuild collision handling mechanism. If two keys produce same hash, collision will be solved through storing two values in chain in table cell.
Its average time complexity is O(1)
What is context?
In Golang, context is a structure, that is used to manage operations flow, cancel certain functions execution when needed and share certain data.
Context can be safely shared between few goroutines.
As I already said, context can be cancelled. This functionality is realized through special channel, that closes when context must be cancelled.
Context can be closed manually, or can have certain timeout or dealine, after what it will be closed automatically.
To sum up, contexts are a tool for managing the execution time and cancellation of operations in networked and multithreaded applications. They help build responsive applications by providing ways to control the duration of operations and safely cancel them.