├── .gitignore ├── Basic ├── README.md ├── interface │ ├── README.md │ ├── interface.go │ └── readme │ │ └── README.ru.md ├── map │ ├── README.md │ ├── map.go │ └── readme │ │ └── README.ru.md ├── readme │ └── README.ru.md ├── slice │ ├── README.md │ ├── readme │ │ └── README.ru.md │ └── slice.go └── string │ ├── README.md │ ├── readme │ └── README.ru.md │ └── string.go ├── Docker ├── README.md └── readme │ └── README.ru.md ├── Kafka ├── README.md └── readme │ └── README.ru.md ├── Multithreading ├── README.md ├── mthreading.go └── readme │ └── README.ru.md ├── Networking ├── README.md └── readme │ └── README.ru.md ├── OOP ├── README.md ├── oop.go └── readme │ └── README.ru.md ├── Patterns ├── README.md └── readme │ └── README.ru.md ├── PostgreSQL ├── README.md └── readme │ └── REDANME.ru.md ├── Practical ├── README.md └── readme │ └── README.ru.md ├── README.md ├── UnderHood └── README.md ├── img ├── basicgo.jpg ├── concurrencyGo.jpeg ├── deadlock.png ├── golang-any-interface-fs8.webp ├── gopher_russian.png ├── gophermap.png ├── gophslice.svg ├── hmap.png ├── map.svg ├── oopgo.jpeg ├── patterns.webp ├── pre_gophers.png ├── rest-api.png ├── rwchan.jpeg └── strings.png └── readme └── README.ru.md /.gitignore: -------------------------------------------------------------------------------- 1 | *.DS_Store 2 | .idea -------------------------------------------------------------------------------- /Basic/README.md: -------------------------------------------------------------------------------- 1 | # Basic knowledge of the language 2 | 3 |

4 | 5 | All data that is stored in memory is essentially just a collection of bits. 6 | And it is the data type that determines how this data will be interpreted and what operations can be performed on it. 7 | Go is a statically typed language, meaning that all data used in a program has a specific type. 8 | 9 | Go has a number of built-in data types and also allows you to define your own types. 10 | ### Data types: 11 | - [String](https://github.com/lumorow/golang-interview-preparation/tree/main/Basic/string) 12 | - [Map](https://github.com/lumorow/golang-interview-preparation/tree/main/Basic/map) 13 | - [Slice](https://github.com/lumorow/golang-interview-preparation/tree/main/Basic/slice) 14 | - [Interface](https://github.com/lumorow/golang-interview-preparation/tree/main/Basic/interface) 15 | 16 | ## README.md 17 | *** 18 | 19 | - eng [English](https://github.com/lumorow/golang-interview-preparation/blob/main/Basic/README.md) 20 | - ru [Русский](https://github.com/lumorow/golang-interview-preparation/blob/main/Basic/readme/README.ru.md) -------------------------------------------------------------------------------- /Basic/interface/README.md: -------------------------------------------------------------------------------- 1 | ## Interface in GO 2 | 3 |

4 | 5 | The interface in the `Go` language is structured like this: 6 | ```golang 7 | // https://golang.org/src/runtime/runtime2.go 8 | 9 | type iface struct { 10 | tab *itab 11 | data unsafe.Pointer 12 | } 13 | ``` 14 | In the `tab` field we store information about the specific type of object that has been converted to an interface. And in the `data` field - a link to the real memory area, 15 | which contains the data of the original object. 16 | 17 | An interface implements that object that defines all the methods specified in the interface. 18 | 19 | An empty interface type does not define methods. He has no rules. And therefore any object satisfies the empty interface. 20 | The empty interface type `interface{}` is a kind of wild card. If you met him in an ad 21 | (variable, function parameter or structure field), then you can use an object of any type. 22 | 23 | ## Benefits of using interfaces 24 | 25 | - Interfaces help reduce duplication, that is, the amount of boilerplate code. 26 | - They make it easier to use stubs instead of real objects in unit tests. 27 | - As an architectural tool, interfaces help decouple parts of your codebase. 28 | 29 | ## Type of object wrapped in interface 30 | You can determine the type of an object wrapped in an empty interface using the `switch` construct 31 | ```golang 32 | func do(obj interface{}) { 33 | switch v := obj.(type) { 34 | case int: 35 | fmt.Printf("Twice %v is %v\n", v, v*2) 36 | case string: 37 | fmt.Printf("%q is %v bytes long\n", v, len(v)) 38 | default: 39 | fmt.Printf("I don't know about type %T!\n", v) 40 | } 41 | } 42 | ``` 43 | You can also use the `reflect` library. When we try to get 44 | The actual source type of the interface object, reflect goes to the `tab` field and gets the type information there. 45 | ```golang 46 | reflect.TypeOf(obj).String() 47 | ``` 48 | We can convert our interface object back to its original type using type assertion syntax: 49 | ```golang 50 | obj, ok := interfaceName.(structName) 51 | fmt.Printf("%#v\n", obj) 52 | fmt.Printf("%t\n", ok) 53 | ``` 54 | 55 | If we compare interface with `nil`, it will be `true` until we wrap an object in it. Even if we put an empty interface 56 | pointer to an object, then interface will no longer be `nil`, since one of the fields of the structure will point to the type of the object (`tab`) 57 | ## Resources 58 | *** 59 | - [Разбираемся с интерфейсами в Go (Блог компании VK)](https://habr.com/ru/companies/vk/articles/463063/) 60 | - [Интерфейсы в Go — как красиво выстрелить себе в ногу](https://habr.com/ru/articles/597461/) 61 | - [Тайные знания о GoLang, которые от вас скрывали (Николай Тузов — Golang)](https://www.youtube.com/watch?v=-cX0CqG6rgA&ab_channel=%D0%9D%D0%B8%D0%BA%D0%BE%D0%BB%D0%B0%D0%B9%D0%A2%D1%83%D0%B7%D0%BE%D0%B2%E2%80%94Golang) 62 | 63 | ## README.md 64 | *** 65 | 66 | - eng [English](https://github.com/lumorow/golang-interview-preparation/blob/main/Basic/interface/README.md) 67 | - ru [Русский](https://github.com/lumorow/golang-interview-preparation/blob/main/Basic/interface/readme/README.ru.md) 68 | 69 | -------------------------------------------------------------------------------- /Basic/interface/interface.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "reflect" 6 | ) 7 | 8 | type MobilePhone struct { 9 | modelName string 10 | price int 11 | } 12 | 13 | type phone interface { 14 | call() 15 | } 16 | 17 | func NewMobilePhone(modelName string, price int) *MobilePhone { 18 | return &MobilePhone{ 19 | modelName: modelName, 20 | price: price, 21 | } 22 | } 23 | 24 | func (m *MobilePhone) call() { 25 | fmt.Printf("%s ringtone tuz tuz...\n", m.modelName) 26 | } 27 | 28 | func main() { 29 | mobPh1 := NewMobilePhone("samsung", 800) 30 | var mobPh2 *MobilePhone 31 | 32 | ph1 := phone(mobPh1) 33 | ph2 := phone(mobPh2) 34 | 35 | fmt.Printf("%t\n", ph1 == nil) // false 36 | fmt.Printf("%t\n", ph2 == nil) // false 37 | 38 | ph1.call() 39 | 40 | fmt.Println("Type ph1 is: " + reflect.TypeOf(ph1).String()) // Type ph1 is: *main.MobilePhone 41 | obj1, ok := ph1.(*MobilePhone) 42 | if ok == true { 43 | fmt.Printf("Success converting to MobilePhone: %#v\n", obj1) 44 | } else { 45 | fmt.Println("Fail converting to MobilePhone") 46 | } 47 | // Success converting to MobilePhone: &main.MobilePhone{modelName:"samsung", price:800} 48 | } 49 | -------------------------------------------------------------------------------- /Basic/interface/readme/README.ru.md: -------------------------------------------------------------------------------- 1 | ## Интерфейсы в GO 2 | 3 |

4 | 5 | Интерфейс в языке `Go` является следующей структурой: 6 | ```golang 7 | // https://golang.org/src/runtime/runtime2.go 8 | 9 | type iface struct { 10 | tab *itab 11 | data unsafe.Pointer 12 | } 13 | ``` 14 | В поле `tab` у нас хранится информация о конкретном типе объекта, который был преобразован в интерфейс. А в поле `data` - ссылка на реальную область памяти, 15 | в которой лежат данные изначального объекта. 16 | 17 | Интерфейс реализует тот объект, что определяет все методы, указанные в интерфейсе. 18 | 19 | Пустой интерфейсный тип не описывает методы. У него нет правил. И поэтому любой объект удовлетворяет пустому интерфейсу. 20 | Пустой интерфейсный тип `interface{}` — своего рода джокер. Если вы встретили его в объявлении 21 | (переменной, параметра функции или поля структуры), то можете использовать объект любого типа. 22 | 23 | ## Преимущества применения интерфейсов 24 | 25 | - Интерфейсы помогают уменьшить дублирование, то есть количество шаблонного кода. 26 | - Они облегчают использование в модульных тестах заглушек вместо реальных объектов. 27 | - Будучи архитектурным инструментом, интерфейсы помогают отвязывать части вашей кодовой базы. 28 | 29 | ## Тип объекта обернутого в интерфейс 30 | Определить тип объекта обернутого в пустой интерфейс можно с помощью конструкции `switch` 31 | ```golang 32 | func do(obj interface{}) { 33 | switch v := obj.(type) { 34 | case int: 35 | fmt.Printf("Twice %v is %v\n", v, v*2) 36 | case string: 37 | fmt.Printf("%q is %v bytes long\n", v, len(v)) 38 | default: 39 | fmt.Printf("I don't know about type %T!\n", v) 40 | } 41 | } 42 | ``` 43 | Также можно использовать библиотеку `reflect`. Когда пытаемся получить 44 | настоящий исходный тип объекта интерфейса, reflect идёт в поле `tab` и получает информацию о типе там. 45 | ```golang 46 | reflect.TypeOf(obj).String() 47 | ``` 48 | Преобразовать наш объект интерфейса обратно к исходному типу можно через синтаксис утверждений типа: 49 | ```golang 50 | obj, ok := interfaceName.(structName) 51 | fmt.Printf("%#v\n", obj) 52 | fmt.Printf("%t\n", ok) 53 | ``` 54 | 55 | Если сравнивать interface с `nil`, то будет `true`, пока мы не обернули в него объект. Даже если мы положим в `interface` пустой 56 | указатель на объект, то interface уже не будет `nil`, так как одно из полей структуры будет указывать на тип объекта (`tab`) 57 | 58 | ## Дополнительный материал 59 | *** 60 | - [Разбираемся с интерфейсами в Go (Блог компании VK)](https://habr.com/ru/companies/vk/articles/463063/) 61 | - [Интерфейсы в Go — как красиво выстрелить себе в ногу](https://habr.com/ru/articles/597461/) 62 | - [Тайные знания о GoLang, которые от вас скрывали (Николай Тузов — Golang)](https://www.youtube.com/watch?v=-cX0CqG6rgA&ab_channel=%D0%9D%D0%B8%D0%BA%D0%BE%D0%BB%D0%B0%D0%B9%D0%A2%D1%83%D0%B7%D0%BE%D0%B2%E2%80%94Golang) 63 | 64 | ## README.md 65 | *** 66 | 67 | - eng [English](https://github.com/lumorow/golang-interview-preparation/blob/main/Basic/interface/README.md) 68 | - ru [Русский](https://github.com/lumorow/golang-interview-preparation/blob/main/Basic/interface/README.ru.md) 69 | 70 | -------------------------------------------------------------------------------- /Basic/map/README.md: -------------------------------------------------------------------------------- 1 | ## Map in GO 2 | 3 |

4 | 5 | A hash table is a data structure that allows you to store key-value pairs, and typically has the following functions: 6 | 7 | - Mapping: map(key) → value 8 | - Insert: insert(map, key, value) 9 | - Removal: delete(map, key) 10 | - Search: lookup(key) → value 11 | 12 | ### Declaring 13 | *** 14 | ```golang 15 | m := make(map[key_type]value_type) 16 | ``` 17 | ```golang 18 | m := new(map[key_type]value_type) 19 | ``` 20 | ```golang 21 | var m map[key_type]value_type // объявление, потом обязательно надо проинициализировать 22 | ``` 23 | ```golang 24 | m := map[key_type]value_type{key1: val1, key2: val2} 25 | ``` 26 | 27 | ### Basic Operations 28 | *** 29 | - Insert: 30 | ```golang 31 | m[key] = value 32 | ``` 33 | - Removal: 34 | ```golang 35 | delete(m, key) 36 | ``` 37 | - Search: 38 | ```golang 39 | value = m[key] 40 | value, ok = m[key] 41 | ``` 42 | 43 | ### Traversing a table in go 44 | *** 45 | A map in Go is `unordered`, that is, not ordered; when iterating through there will always be a different order of elements. 46 | The search location is determined randomly (source language runtime code): 47 | 48 | ```golang 49 | // mapiterinit initializes the hiter struct used for ranging over maps. 50 | func mapiterinit(t *maptype, h *hmap, it *hiter) {... 51 | // decide where to start 52 | r := uintptr(fastrand()) 53 | ... 54 | it.startBucket = r & bucketMask(h.B)...} 55 | ``` 56 | Example: 57 | ```golang 58 | package main 59 | 60 | import "fmt" 61 | 62 | func main() { 63 | m := map[int]bool{} 64 | for i := 0; i < 5; i++ { 65 | m[i] = ((i % 2) == 0) 66 | } 67 | for k, v := range m { 68 | fmt.Printf("key: %d, value: %t\n", k, v) 69 | } 70 | } 71 | ``` 72 | Launch 1: 73 | 74 | key: 3, value: false 75 | key: 4, value: true 76 | key: 0, value: true 77 | key: 1, value: false 78 | key: 2, value: true 79 | 80 | Launch 2: 81 | 82 | key: 4, value: true 83 | key: 0, value: true 84 | key: 1, value: false 85 | key: 2, value: true 86 | key: 3, value: false 87 | 88 | ### Go table lookup 89 | Thanks to `«multiple assignment»` we can use the second variable `ok` to check the presence of a key in the map. 90 | If there is no key, `null value of type` and `false` will be returned. 91 | *** 92 | ```golang 93 | package main 94 | 95 | import ( 96 | "fmt" 97 | ) 98 | 99 | func main() { 100 | m := map[int]int{0: 50, 1: -100} 101 | m2, ok := m[2] 102 | m3 := m[3] 103 | if !ok { 104 | m2 = 20 105 | } 106 | fmt.Println(m, m[0], m[1], m2, m3) // map[0:0 1:10] 0 10 20 0 107 | } 108 | ``` 109 | 110 | ### Map element address 111 | *** 112 | ```golang 113 | package main 114 | 115 | import ( 116 | "fmt" 117 | ) 118 | 119 | func main() { 120 | m := make(map[int]int) 121 | m[1] = 10 122 | a := &m[1] 123 | fmt.Println(m[1], *a) 124 | } 125 | ``` 126 | `Go` says: `"cannot take the address of m[1]"`. Due to data evacuation, map growth. The item can be moved to a new bucket and the address will be 127 | already point to the removed element. 128 | 129 | ### Definition 130 | *** 131 | A map in Go is simply a pointer to an hmap structure. This is the answer to the question why, given that the map is passed to the function by 132 | value, the values themselves that lie in it change - it’s all about the pointer. The hmap structure also contains the following: quantity 133 | elements, the number of “buckets” (represented as a logarithm to speed up calculations), seed for hash randomization (to make it more difficult 134 | ddosit - try to select the keys so that there will be continuous collisions), all sorts of service fields and, most importantly, a pointer to buckets, 135 | where the values are stored. 136 | 137 | ```golang 138 | // A header for a Go map. 139 | type hmap struct { 140 | // Note: the format of the hmap is also encoded in cmd/compile/internal/gc/reflect.go. 141 | // Make sure this stays in sync with the compiler's definition. 142 | count int // # live cells == size of map. Must be first (used by len() builtin) 143 | flags uint8 144 | B uint8 // log_2 of # of buckets (can hold up to loadFactor * 2^B items) 145 | noverflow uint16 // approximate number of overflow buckets; see incrnoverflow for details 146 | hash0 uint32 // hash seed 147 | // buckets unsafe.Pointer // array of 2^B Buckets. may be nil if count==0. 148 | oldbuckets unsafe.Pointer // previous bucket array of half the size, non-nil only when growing 149 | nevacuate uintptr // progress counter for evacuation (buckets less than this have been evacuated) 150 | } 151 | ``` 152 | ![hmap](../../img/hmap.png) 153 | 154 | The picture shows a schematic representation of the structure in memory - there is a hmap header, the pointer to which is map in Go 155 | (it is created when declared using var, but is not initialized, which is why the program crashes when trying 156 | inserts). The buckets field is a storage of key-value pairs, there are several such “buckets”, each containing 8 pairs. 157 | First, the “bucket” contains slots for additional hash bits (e0..e7 is called e - because extra hash bits). 158 | Next are the keys and values, first a list of all keys, then a list of all values. 159 | 160 | The hash function determines which “bucket” we put the value into; inside each “bucket” there can be up to 8 collisions; 161 | at the end of each “bucket” there is a pointer to an additional one, if the previous one suddenly overflowed. 162 | 163 | ### How does map grow? 164 | *** 165 | In the source code you can find the line: 166 | 167 | > // Maximum average load of a bucket that triggers growth is 6.5. 168 | 169 | that is, if each “bucket” has on average more than 6.5 elements, the buckets array increases. 170 | In this case, an array 2 times larger is allocated, and the old data is copied into it in small portions every insertion 171 | or removal so as not to create very large delays. Therefore, all operations will be a little slower in the process 172 | evacuation of data (during search too, we have to search in two places). After a successful evacuation they begin 173 | use new data. 174 | 175 | ## Resources 176 | *** 177 | - [Go maps in action](https://go.dev/blog/maps) 178 | - [Знакомство с картами в Go](https://www.digitalocean.com/community/tutorials/understanding-maps-in-go-ru) 179 | - [Хэш таблицы в Go. Детали реализации](https://habr.com/ru/articles/457728/) 180 | - [Hashmap(map) по версии Golang вместе с реализацией на дженериках](https://habr.com/ru/articles/704796/) 181 | - [Как на самом деле устроен тип Map в Golang? (Николай Тузов — Golang)](https://www.youtube.com/watch?v=P_SXTUiA-9Y&ab_channel=%D0%9D%D0%B8%D0%BA%D0%BE%D0%BB%D0%B0%D0%B9%D0%A2%D1%83%D0%B7%D0%BE%D0%B2%E2%80%94Golang) 182 | 183 | ## README.md 184 | *** 185 | 186 | - eng [English](https://github.com/lumorow/golang-interview-preparation/blob/main/Basic/map/README.md) 187 | - ru [Русский](https://github.com/lumorow/golang-interview-preparation/blob/main/Basic/map/readme/README.ru.md) -------------------------------------------------------------------------------- /Basic/map/map.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func fn1(m map[int]int) { 6 | m = make(map[int]int) 7 | fmt.Println("m == nil in fn?:", m == nil) // m == nil in fn?: false 8 | } 9 | 10 | func fn2(m map[string]int) { 11 | m["c"] = 3 12 | m["d"] = 4 13 | m["e"] = 5 14 | m["f"] = 6 15 | m["g"] = 7 16 | m["h"] = 8 17 | } 18 | 19 | //func main() { 20 | // var m map[int]int 21 | // fn1(m) 22 | // fmt.Println("m == nil in main?:", m == nil) // m == nil in main?: true 23 | //} 24 | 25 | func main() { 26 | m := map[string]int{"a": 1, "b": 2} 27 | fn2(m) 28 | fmt.Println(m) // map[a:1 b:2 c:3 d:4 e:5 f:6 g:7 h:8] 29 | fmt.Println(len(m)) // 8 30 | } 31 | -------------------------------------------------------------------------------- /Basic/map/readme/README.ru.md: -------------------------------------------------------------------------------- 1 | ## Карты в GO 2 | 3 |

4 | 5 | Хэш таблица - это структура данных, которая позволяет хранить пары ключ-значение, и, как правило, обладающая функциями: 6 | 7 | - Маппинга: map(key) → value 8 | - Вставки: insert(map, key, value) 9 | - Удаления: delete(map, key) 10 | - Поиска: lookup(key) → value 11 | 12 | ### Объявление 13 | *** 14 | ```golang 15 | m := make(map[key_type]value_type) 16 | ``` 17 | ```golang 18 | m := new(map[key_type]value_type) 19 | ``` 20 | ```golang 21 | var m map[key_type]value_type // объявление, потом обязательно надо проинициализировать 22 | ``` 23 | ```golang 24 | m := map[key_type]value_type{key1: val1, key2: val2} 25 | ``` 26 | 27 | ### Основные операции 28 | *** 29 | - Вставка: 30 | ```golang 31 | m[key] = value 32 | ``` 33 | - Удаление: 34 | ```golang 35 | delete(m, key) 36 | ``` 37 | - Поиск: 38 | ```golang 39 | value = m[key] 40 | value, ok = m[key] 41 | ``` 42 | 43 | ### Обход таблицы в go 44 | *** 45 | Мапа в Go `unordered`, то есть не упорядоченная, при переборе будет всегда разный порядок элементов. 46 | Место поиска определяется рандомно (исходник кода рантайма языка): 47 | ```golang 48 | // mapiterinit initializes the hiter struct used for ranging over maps. 49 | func mapiterinit(t *maptype, h *hmap, it *hiter) {... 50 | // decide where to start 51 | r := uintptr(fastrand()) 52 | ... 53 | it.startBucket = r & bucketMask(h.B)...} 54 | ``` 55 | Пример: 56 | ```golang 57 | package main 58 | 59 | import "fmt" 60 | 61 | func main() { 62 | m := map[int]bool{} 63 | for i := 0; i < 5; i++ { 64 | m[i] = ((i % 2) == 0) 65 | } 66 | for k, v := range m { 67 | fmt.Printf("key: %d, value: %t\n", k, v) 68 | } 69 | } 70 | ``` 71 | Запуск 1: 72 | 73 | key: 3, value: false 74 | key: 4, value: true 75 | key: 0, value: true 76 | key: 1, value: false 77 | key: 2, value: true 78 | 79 | Запуск 2: 80 | 81 | key: 4, value: true 82 | key: 0, value: true 83 | key: 1, value: false 84 | key: 2, value: true 85 | key: 3, value: false 86 | 87 | ### Поиск в таблице Go 88 | Благодаря `«multiple assignment»` мы можем проверять с помощью второй переменной `ok` наличие ключа в мапе. 89 | При отсутствии ключа будет возвращаться `«нулевое значение типа»` и `false`. 90 | *** 91 | ```golang 92 | package main 93 | 94 | import ( 95 | "fmt" 96 | ) 97 | 98 | func main() { 99 | m := map[int]int{0: 50, 1: -100} 100 | m2, ok := m[2] 101 | m3 := m[3] 102 | if !ok { 103 | m2 = 20 104 | } 105 | fmt.Println(m, m[0], m[1], m2, m3) // map[0:0 1:10] 0 10 20 0 106 | } 107 | ``` 108 | 109 | ### Адрес элемента map 110 | *** 111 | ```golang 112 | package main 113 | 114 | import ( 115 | "fmt" 116 | ) 117 | 118 | func main() { 119 | m := make(map[int]int) 120 | m[1] = 10 121 | a := &m[1] 122 | fmt.Println(m[1], *a) 123 | } 124 | ``` 125 | `Go` говорит: `«cannot take the address of m[1]»`. Из - за эвакуации данных, роста мапы. Элемент может перенестись в новый бакет, и адрес будет 126 | уже указывать на удаленный элемент. 127 | 128 | ### Определение 129 | *** 130 | Мапа в Go — это просто указатель на структуру hmap. Это и является ответом на вопрос, почему при том, что мапа передается в функцию по 131 | значению, сами значения, лежащие в ней меняются — все дело в указателе. Так же структура hmap содержит в себе следующее: количество 132 | элементов, количество «ведер» (представлено в виде логарифма для ускорения вычислений), seed для рандомизации хэшей (чтобы было сложнее 133 | заddosить — попытаться подобрать ключи так, что будут сплошные коллизии), всякие служебные поля и главное указатель на buckets, 134 | где хранятся значения. 135 | ```golang 136 | // A header for a Go map. 137 | type hmap struct { 138 | // Note: the format of the hmap is also encoded in cmd/compile/internal/gc/reflect.go. 139 | // Make sure this stays in sync with the compiler's definition. 140 | count int // # live cells == size of map. Must be first (used by len() builtin) 141 | flags uint8 142 | B uint8 // log_2 of # of buckets (can hold up to loadFactor * 2^B items) 143 | noverflow uint16 // approximate number of overflow buckets; see incrnoverflow for details 144 | hash0 uint32 // hash seed 145 | // buckets unsafe.Pointer // array of 2^B Buckets. may be nil if count==0. 146 | oldbuckets unsafe.Pointer // previous bucket array of half the size, non-nil only when growing 147 | nevacuate uintptr // progress counter for evacuation (buckets less than this have been evacuated) 148 | } 149 | ``` 150 | ![hmap](../../../img/hmap.png) 151 | 152 | На картинке схематичное изображение структуры в памяти — есть хэдер hmap, указатель на который и есть map в Go 153 | (именно он создается при объявлении с помощью var, но не инициализируется, из-за чего падает программа при попытке 154 | вставки). Поле buckets — хранилище пар ключ-значение, таких «ведер» несколько, в каждом лежит 8 пар. 155 | Сначала в «ведре» лежат слоты для дополнительных битов хэшей (e0..e7 названо e — потому что extra hash bits). 156 | Далее лежат ключи и значения как сначала список всех ключей, потом список всех значений. 157 | 158 | По хэш функции определяется в какое «ведро» мы кладем значение, внутри каждого «ведра» может лежать до 8 коллизий, в конце каждого «ведра» есть указатель на дополнительное, если вдруг предыдущее переполнилось. 159 | 160 | ### Как растет map? 161 | *** 162 | В исходном коде можно найти строчку: 163 | 164 | > // Maximum average load of a bucket that triggers growth is 6.5. 165 | 166 | то есть, если в каждом «ведре» в среднем более 6,5 элементов, происходит увеличение массива buckets. 167 | При этом выделяется массив в 2 раза больше, а старые данные копируются в него маленькими порциями каждые вставку 168 | или удаление, чтобы не создавать очень крупные задержки. Поэтому все операции будут чуть медленнее в процессе 169 | эвакуации данных (при поиске тоже, нам же приходится искать в двух местах). После успешной эвакуации начинают 170 | использоваться новые данные. 171 | 172 | ## Дополнительный материал 173 | *** 174 | - [Go maps in action](https://go.dev/blog/maps) 175 | - [Знакомство с картами в Go](https://www.digitalocean.com/community/tutorials/understanding-maps-in-go-ru) 176 | - [Хэш таблицы в Go. Детали реализации](https://habr.com/ru/articles/457728/) 177 | - [Hashmap(map) по версии Golang вместе с реализацией на дженериках](https://habr.com/ru/articles/704796/) 178 | - [Как на самом деле устроен тип Map в Golang? (Николай Тузов — Golang)](https://www.youtube.com/watch?v=P_SXTUiA-9Y&ab_channel=%D0%9D%D0%B8%D0%BA%D0%BE%D0%BB%D0%B0%D0%B9%D0%A2%D1%83%D0%B7%D0%BE%D0%B2%E2%80%94Golang) 179 | 180 | ## README.md 181 | *** 182 | 183 | - eng [English](https://github.com/lumorow/golang-interview-preparation/blob/main/Basic/map/README.md) 184 | - ru [Русский](https://github.com/lumorow/golang-interview-preparation/blob/main/Basic/map/readme/README.ru.md) -------------------------------------------------------------------------------- /Basic/readme/README.ru.md: -------------------------------------------------------------------------------- 1 | ## Основные знания по языку 2 | 3 |

4 | 5 | Все данные, которые хранятся в памяти, по сути представляют просто набор битов. 6 | И именно тип данных определяет, как будут интерпретироваться эти данные и какие операции с ними можно производить. 7 | Язык Go является статически типизированным языком, то есть все используемые в программе данные имеют определенный тип. 8 | 9 | Go имеет ряд встроенных типов данных, а также позволяет определять свои типы. 10 | ### Data types: 11 | - [String (Строка)](https://github.com/lumorow/golang-interview-preparation/tree/main/Basic/string/readme/README.ru.md) 12 | - [Map (Карта)](https://github.com/lumorow/golang-interview-preparation/tree/main/Basic/map/readme/README.ru.md) 13 | - [Slice (Срез)](https://github.com/lumorow/golang-interview-preparation/tree/main/Basic/slice/readme/README.ru.md) 14 | - [Interface (Интерфейс)](https://github.com/lumorow/golang-interview-preparation/tree/main/Basic/interface/readme/README.ru.md) -------------------------------------------------------------------------------- /Basic/slice/README.md: -------------------------------------------------------------------------------- 1 | ## Slice in Go 2 | 3 | Slices are a structure that we will talk about next. 4 |

5 | 6 | ### Declaration 7 | *** 8 | - First option 9 | ```golang 10 | planets := []string{ 11 | "Mercury", 12 | "Venus", 13 | "Earth", 14 | "Mars", 15 | "Jupiter", 16 | "Saturn", 17 | "Uranus", 18 | "Neptune", 19 | } 20 | ``` 21 | 22 | - Second option 23 | ```golang 24 | planets := make([]string, len, cap) // make 25 | ``` 26 | 27 | - Third option 28 | ```golang 29 | nums := [...]int{ 30 | 1, 31 | 2, 32 | 3, 33 | 4, 34 | 5, 35 | 6, 36 | } 37 | 38 | numsSl := nums[:] // composite literal, declare a slice from an array 39 | ``` 40 | ### Definition 41 | *** 42 | The difference between a slice and an array is as follows: 43 | 44 | - A slice is a reference to an array; 45 | - A slice can dynamically allocate memory and change its size; 46 | - A slice is represented by the following structure in the `GO` sources 47 | 48 | ```golang 49 | type slice struct { 50 | array unsafe.Pointer 51 | len int 52 | cap int 53 | } 54 | ``` 55 | `len (length)` — current cut length, `cap` (capacity) — length of the internal array. 56 | 57 | Both of these options can be specified when calling the make function: 58 | ```golang 59 | sl := make( 60 | []int, 61 | 10, // len 62 | 10, // cap 63 | ) 64 | ``` 65 | `cap` — a key parameter for memory allocation that affects the performance of inserting into a slice. 66 | 67 | ### Let's consider the behavior of a slice as its size increases. 68 | *** 69 | ```golang 70 | a := []int{99} 71 | b := a[0:1] 72 | b[0] = 0 73 | 74 | fmt.Println(a) 75 | // [0] 76 | 77 | a[0] = 99 78 | 79 | fmt.Println(b) 80 | // [99] 81 | ``` 82 | 83 | We got slice `b` from slice `a`. Next we see that changes in one slice affect the other. Both slices refer to the same array. 84 | Now let's complete the example by inserting elements into slice `a`: 85 | Let's consider the behavior of a slice as its size increases. 86 | ```golang 87 | a := []int{99} 88 | b := a[0:1] 89 | 90 | a = append(a, 100) 91 | a[0] = 0 92 | 93 | fmt.Println(a, b) 94 | // [0 100] [99] 95 | ``` 96 | Now the values of the slice elements are different. Now the slices refer to a different array. 97 | 98 | The `growslice` function from the source code is responsible for this. 99 | Changing the `cap` of a slice will always copy the array data: 100 | ```golang 101 | memmove(p, old.array, lenmem) 102 | ``` 103 | `cap` will change as follows 104 | ```golang 105 | const threshold = 256 106 | if old.cap < threshold { 107 | newcap = doublecap 108 | } else { 109 | // Check 0 < newcap to detect overflow 110 | // and prevent an infinite loop. 111 | for 0 < newcap && newcap < cap { 112 | // Transition from growing 2x for small slices 113 | // to growing 1.25x for large slices. This formula 114 | // gives a smooth-ish transition between the two. 115 | newcap += (newcap + 3*threshold) / 4 116 | } 117 | ``` 118 | 119 | ## Removing an element from a slice 120 | *** 121 | To remove the `i` element from a slice, you need to select the elements before and after it, 122 | and then combine the two new slices into one. 123 | ```golang 124 | slice = append(slice[:i], slice[i+1:]...) 125 | ``` 126 | 127 | ## Resources 128 | *** 129 | - [Go Slices: usage and internals](https://go.dev/blog/slices-intro) 130 | - [Arrays and Slices in Go](https://www.digitalocean.com/community/tutorials/understanding-arrays-and-slices-in-go) 131 | - [GoLang Slice в деталях, простым языком (Николай Тузов — Golang)](https://www.youtube.com/watch?v=10LW7NROfOQ&ab_channel=%D0%9D%D0%B8%D0%BA%D0%BE%D0%BB%D0%B0%D0%B9%D0%A2%D1%83%D0%B7%D0%BE%D0%B2%E2%80%94Golang) 132 | 133 | ## README.md 134 | *** 135 | - eng [English](https://github.com/lumorow/golang-interview-preparation/blob/main/Basic/slice/README.md) 136 | - ru [Русский](https://github.com/lumorow/golang-interview-preparation/blob/main/Basic/slice/readme/README.ru.md) -------------------------------------------------------------------------------- /Basic/slice/readme/README.ru.md: -------------------------------------------------------------------------------- 1 | ## Срезы в Go 2 | 3 | Срезы это структура, о которой мы поговорим далее. 4 |

5 | 6 | ### Обявление 7 | *** 8 | - Первый вариант 9 | ```golang 10 | planets := []string{ 11 | "Меркурий", 12 | "Венера", 13 | "Земля", 14 | "Марс", 15 | "Юпитер", 16 | "Сатурн", 17 | "Уран", 18 | "Нептун", 19 | } 20 | ``` 21 | 22 | - Второй вариант 23 | ```golang 24 | planets := make([]string, len, cap) // через make 25 | ``` 26 | 27 | - Третий вариант 28 | ```golang 29 | nums := [...]int{ 30 | 1, 31 | 2, 32 | 3, 33 | 4, 34 | 5, 35 | 6 36 | } 37 | 38 | numsSl := nums[:] // через композитный литерал объявляем срез из массива 39 | ``` 40 | ### Определение 41 | *** 42 | От массива срез отличает следующее: 43 | 44 | - Срез является ссылкой на массив; 45 | - Срез может динамически аллоцировать память и менять свой размер; 46 | - Срез представляется следующей структурой в исходниках `GO` 47 | 48 | ```golang 49 | type slice struct { 50 | array unsafe.Pointer 51 | len int 52 | cap int 53 | } 54 | ``` 55 | `len (length, длина)` — текущая длина среза, `cap` (capacity, вместимость) — длина внутреннего массива. 56 | 57 | Оба эти параметра можно задать при вызове функции make: 58 | ```golang 59 | sl := make( 60 | []int, 61 | 10, // len 62 | 10, // cap 63 | ) 64 | ``` 65 | `Cap` — ключевой параметр для аллокации памяти, влияет на производительность вставки в срез. 66 | 67 | ### Рассмотрим поведение среза при увеличении его размера. 68 | *** 69 | ```golang 70 | a := []int{99} 71 | b := a[0:1] 72 | b[0] = 0 73 | 74 | fmt.Println(a) 75 | // [0] 76 | 77 | a[0] = 99 78 | 79 | fmt.Println(b) 80 | // [99] 81 | ``` 82 | 83 | Мы получили срез `b` из среза `a`. Далее видим, что изменение в одном срезе влияют на другой. Оба среза ссылаются на один и тот же массив. 84 | Теперь дополним пример вставкой элементов в срез `a`: 85 | Рассмотрим поведение среза при увеличении его размера. 86 | ```golang 87 | a := []int{99} 88 | b := a[0:1] 89 | 90 | a = append(a, 100) 91 | a[0] = 0 92 | 93 | fmt.Println(a, b) 94 | // [0 100] [99] 95 | ``` 96 | Теперь значения у элементов срезов разные. Теперь срезы ссылаются на разный массив. 97 | 98 | За это отвечает функция `growslice` из исходников. 99 | В результате изменения `cap` среза всегда произойдет копирование данных массива: 100 | ```golang 101 | memmove(p, old.array, lenmem) 102 | ``` 103 | Изменяться `cap` будет следующем образом 104 | ```golang 105 | const threshold = 256 106 | if old.cap < threshold { 107 | newcap = doublecap 108 | } else { 109 | // Check 0 < newcap to detect overflow 110 | // and prevent an infinite loop. 111 | for 0 < newcap && newcap < cap { 112 | // Transition from growing 2x for small slices 113 | // to growing 1.25x for large slices. This formula 114 | // gives a smooth-ish transition between the two. 115 | newcap += (newcap + 3*threshold) / 4 116 | } 117 | ``` 118 | 119 | ## Удаление элемента из среза 120 | *** 121 | Чтобы удалить `i-ый` элемент из среза, нужно выделить элементы до него и после него, 122 | а потом объединить два новых среза в один. 123 | ```golang 124 | slice = append(slice[:i], slice[i+1:]...) 125 | ``` 126 | 127 | ## Дополнительный материал 128 | *** 129 | - [Go Slices: usage and internals](https://go.dev/blog/slices-intro) 130 | - [Массивы и срезы в Go](https://www.digitalocean.com/community/tutorials/understanding-arrays-and-slices-in-go-ru) 131 | - [GoLang Slice в деталях, простым языком (Николай Тузов — Golang)](https://www.youtube.com/watch?v=10LW7NROfOQ&ab_channel=%D0%9D%D0%B8%D0%BA%D0%BE%D0%BB%D0%B0%D0%B9%D0%A2%D1%83%D0%B7%D0%BE%D0%B2%E2%80%94Golang) 132 | 133 | ## README.md 134 | *** 135 | 136 | - eng [English](https://github.com/lumorow/golang-interview-preparation/blob/main/Basic/slice/README.md) 137 | - ru [Русский](https://github.com/lumorow/golang-interview-preparation/blob/main/Basic/slice/readme/README.ru.md) -------------------------------------------------------------------------------- /Basic/slice/slice.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func getSlice1(sl []int) { 6 | sl[0] = -100 7 | sl = append(sl, 11) 8 | } 9 | 10 | func getSlice2(sl *[]int) { 11 | s := *sl 12 | s[0] = -100 13 | *sl = append(*sl, 11) 14 | } 15 | 16 | func main() { 17 | sl3 := make([]int, 0, 10) //len: 0; cap: 10 18 | 19 | sl1 := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} //len: 10; cap: 10 20 | sl2 := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} 21 | for i := 1; i < cap(sl3); i++ { 22 | sl3 = append(sl3, i) 23 | } 24 | 25 | getSlice1(sl1) 26 | getSlice1(sl3) 27 | getSlice2(&sl2) 28 | 29 | fmt.Printf("sl1: %d; cap: %d; len: %d\n", sl1, cap(sl1), len(sl1)) // sl1: [-100 2 3 4 5 6 7 8 9 10]; cap: 10; len: 10 30 | fmt.Printf("sl2: %d; cap: %d; len: %d\n", sl2, cap(sl2), len(sl2)) // sl2: [-100 2 3 4 5 6 7 8 9 10 11]; cap: 20; len: 11 31 | fmt.Printf("sl3: %d; cap: %d; len: %d\n", sl3, cap(sl3), len(sl3)) // sl3: [-100 2 3 4 5 6 7 8 9]; cap: 10; len: 9 32 | } 33 | 34 | // 35 | //func main() { 36 | // slice := []string{"a", "a"} 37 | // 38 | // func(slice []string) { 39 | // slice = append(slice, "a") 40 | // slice[0] = "b" 41 | // slice[1] = "b" 42 | // fmt.Print(slice) 43 | // }(slice) 44 | // fmt.Print(slice) // [b b a][a a] 45 | //} 46 | -------------------------------------------------------------------------------- /Basic/string/README.md: -------------------------------------------------------------------------------- 1 | ## String in GO 2 | 3 |

4 | 5 | `Strings` in `Go` are encoded in `UTF-8`, one of several standard Unicode encoding characters. 6 | `UTF-8` is an efficient variable-length encoding. A single code can use 8, 16, or 32 bits of memory. 7 | ### Declaring Go string queries 8 | *** 9 | 10 | ```golang 11 | str := "hello" 12 | var str = "hello" 13 | var str string = "hello" 14 | ``` 15 | If you declare a variable without specifying a value, 16 | it will be initialized to zero. 17 | The null value of type `string` is empty quotes (""): 18 | ```golang 19 | var str string 20 | ``` 21 | 22 | ### Is it possible to change strings in Golang? 23 | *** 24 | 25 | Strings in `Golang` are not meant to be manipulated. 26 | You can assign another string to a variable, but 27 | the strings themselves cannot be edited: 28 | ```golang 29 | str := "hello" 30 | str = "home" // YES 31 | str[0] = 'q' // NO 32 | ``` 33 | 34 | ### Decoding strings into runes 35 | *** 36 | 37 | - Strings use an encoding called `UTF-8`, where each character requires 38 | from 1 to 4 bytes; 39 | - `byte` is another name for type `uint8`, and `rune` is another name 40 | type `int32`; 41 | - The range keyword can decode a `UTF-8` encoded string into runs. 42 | 43 | ### An efficient way to concatenate strings 44 | *** 45 | 46 | ```golang 47 | func concat2builder(x, y string) string { 48 | var builder strings.Builder 49 | builder.Grow(len(x) + len(y)) // this line allocates memory 50 | builder.WriteString(x) 51 | builder.WriteString(y) 52 | return builder.String() 53 | } 54 | ``` 55 | 56 | ## README.md 57 | *** 58 | 59 | - eng [English](https://github.com/lumorow/golang-interview-preparation/blob/main/Basic/string/README.md) 60 | - ru [Русский](https://github.com/lumorow/golang-interview-preparation/blob/main/Basic/string/readme/README.ru.md) -------------------------------------------------------------------------------- /Basic/string/readme/README.ru.md: -------------------------------------------------------------------------------- 1 | ## Строки в GO 2 | 3 |

4 | 5 | 6 | `Строки` в Go закодированы в `UTF-8`, одном из нескольких стандартных символов кодирования юникод. 7 | `UTF-8` является эффективным кодированием переменной длины. Один код может использовать память объемом 8, 16 или 32 бита. 8 | ### Объявление строк в GO 9 | *** 10 | 11 | ```golang 12 | str := "hello" 13 | var str = "hello" 14 | var str string = "hello" 15 | ``` 16 | Если объявить переменную без указания значения, 17 | оно будет инициализировано нулевым значением. 18 | Нулевое значение типа `string` представляет собой пустые кавычки (""): 19 | ```golang 20 | var str string 21 | ``` 22 | 23 | ### Можно ли менять строки в Golang? 24 | *** 25 | 26 | Строки в `Golang` не предназначены для изменений. 27 | Вы можете присвоить переменной другую строку, но 28 | сами строки редактировать нельзя: 29 | ```golang 30 | str := "hello" 31 | str = "home" // Можно 32 | str[0] = 'q' // Нельзя 33 | ``` 34 | 35 | ### Перевод строк в руны 36 | *** 37 | 38 | - Строки используют кодировку `UTF-8`, где каждый символ требует 39 | от 1 до 4 байт; 40 | - `byte` является другим названием типа `uint8`, a `rune` является другим названием типа `int32`; 41 | - Ключевое слово range может декодировать закодированную строку `UTF-8` в руны. 42 | 43 | ### Эффективный способ объединения строк 44 | *** 45 | 46 | ```golang 47 | func concat2builder(x, y string) string { 48 | var builder strings.Builder 49 | builder.Grow(len(x) + len(y)) // выделение памяти 50 | builder.WriteString(x) 51 | builder.WriteString(y) 52 | return builder.String() 53 | } 54 | ``` 55 | 56 | ## README.md 57 | *** 58 | 59 | - eng [English](https://github.com/lumorow/golang-interview-preparation/blob/main/Basic/string/README.md) 60 | - ru [Русский](https://github.com/lumorow/golang-interview-preparation/blob/main/Basic/string/readme/README.ru.md) -------------------------------------------------------------------------------- /Basic/string/string.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "unicode/utf8" 6 | ) 7 | 8 | func main() { 9 | str := "ご気分はいかがですか?" 10 | 11 | fmt.Println(str) 12 | for i, c := range str { 13 | fmt.Printf("%v %c\n", i, c) 14 | } 15 | fmt.Println(len(str), "bytes") // Output: 31 bytes 16 | fmt.Println(utf8.RuneCountInString(str), "runes") // Output: 11 runes 17 | 18 | c, size := utf8.DecodeRuneInString(str) 19 | fmt.Printf("First rune: %c %v bytes", c, size) // Output: First rune: ご 3 bytes 20 | } 21 | -------------------------------------------------------------------------------- /Docker/README.md: -------------------------------------------------------------------------------- 1 | # Docker 2 | Docker is a tool for building packages, delivering and running applications in "containers" 3 | 4 | ## What is a Docker container? 5 | 6 | A container is a basic unit of software that encloses code and all its dependencies 7 | to ensure that the application runs transparently, quickly and reliably, regardless of the environment. Container 8 | Docker can be built using a Docker image. This is an executable software package, 9 | containing everything necessary to run the application, for example, system programs, libraries, code, runtime environments 10 | and settings. 11 | 12 | ## Components of the Docker architecture 13 | 14 | The main components of the Docker architecture are: 15 | 16 | - `server`, contains the Docker service, images and containers. The service contacts `Registry`, 17 | images - metadata for applications running in Docker containers. 18 | - `client`, used to run various actions on the Docker server. 19 | - `registry`, used to store images. There are public ones available to everyone, for example, `Docker Hub` and `Docker Cloud`. 20 | 21 | ## The most important Docker commands 22 | 23 | The most important Docker commands are: 24 | - `build`, building an image for Docker 25 | - `create`, creating a new container 26 | - `kill`. forced stop of the container 27 | - `dockerd`, start the Docker service 28 | - `commit`, creating a new image from changes in the container 29 | ## Docker container state 30 | 31 | To determine the status, you need to run the command: 32 | 33 | > docker ps -a 34 | 35 | This command will list all available containers with their status on the server. 36 | From this list you need to select the required container and find out its status. 37 | 38 | ## Docker image, Docker run 39 | 40 | A Docker image is a set of files combined with settings that can be used to create instances of 41 | which run in separate containers as isolated processes. The image is built using 42 | instructions for obtaining the full executable version of the application, depending on the version of the server kernel. 43 | The `Docker run` command is used to create such instances, called containers, run by 44 | using Docker images. When running one image, the user can create multiple containers. 45 | 46 | ## Differences between virtualization and containerization 47 | 48 | `Virtualization` allows you to run multiple operating systems on one physical server. 49 | `Containerization` runs on the same operating system in which the applications are packaged 50 | into containers and run on one server/virtual machine. 51 | 52 | ## Advanced Docker commands 53 | 54 | The most important of them: 55 | 56 | - `docker -version`: find out the installed Docker version; 57 | - `docker ps`: list all running containers along with additional information about them; 58 | - `docker ps -a`: list all containers, including stopped ones, along with additional information about them; 59 | - `docker exec`: enter the container and execute a command in it; 60 | - `docker build`: build an image from a Dockerfile; 61 | - `docker rm`: delete the container with the specified identifier; 62 | - `docker rmi`: delete the image with the specified identifier; 63 | - `docker info`: get extended information about the installed Docker, for example, how many containers, images are running, kernel version, available RAM, etc.; 64 | - `docker cp`: save the file from the container to the local system; 65 | - `docker history`: show the history of the image with the specified name. 66 | 67 | ## Docker and Docker Compose 68 | 69 | Docker is used to manage the individual containers (services) that make up an application. 70 | 71 | Docker Compose is used to simultaneously manage multiple containers that make up an application. 72 | This tool offers the same capabilities as Docker, but allows you to work with more complex applications. 73 | 74 | ## Resources 75 | 76 | - [50 questions about Docker](https://habr.com/ru/companies/slurm/articles/528206/) 77 | - [20 common Docker interview questions](https://itsecforu.ru/2020/01/15/%F0%9F%90%B3-20-%D1%80%D0%B0%D1%81%D0%BF%D1%80%D0%BE%D1%81%D1%82%D1%80%D0%B0%D0%BD%D0%B5%D0%BD%D0%BD%D1%8B%D1%85-%D0%B2%D0%BE%D0%BF%D1%80%D0%BE%D1%81%D0%BE%D0%B2-%D0%BF%D1%80%D0%BE-docker-%D0%BD%D0%B0/) 78 | - [Docker Guide](https://medium.com/nuances-of-programming/%D1%80%D1%83%D0%BA%D0%BE%D0%B2%D0%BE%D0%B4%D1%81%D1%82%D0%B2%D0%BE-%D0%BF%D0%BE-docker-%D1%87%D0%B0%D1%81%D1%82%D1%8C-1-%D0%BE%D0%B1%D1%80%D0%B0%D0%B7-%D0%BA%D0%BE%D0%BD%D1%82%D0%B5%D0%B9%D0%BD%D0%B5%D1%80-%D1%81%D0%BE%D0%BF%D0%BE%D1%81%D1%82%D0%B0%D0%B2%D0%BB%D0%B5%D0%BD%D0%B8%D0%B5-%D0%BF%D0%BE%D1%80%D1%82%D0%BE%D0%B2-%D0%B8-%D0%BE%D1%81%D0%BD%D0%BE%D0%B2%D0%BD%D1%8B%D0%B5-%D0%BA%D0%BE%D0%BC%D0%B0%D0%BD%D0%B4%D1%8B-4997f2968925#:~:text=%D0%BD%D0%B0%D1%81%D1%82%D1%80%D0%BE%D0%B5%D0%BD%D0%BD%D0%BE%D0%B5%20%D1%81%D0%BE%D0%BF%D0%BE%D1%81%D1%82%D0%B0%D0%B2%D0%BB%D0%B5%D0%BD%D0%B8%D0%B5%20%D0%BF%D0%BE%D1%80%D1%82%D0%BE%D0%B2-,%D0%92%D1%8B%D0%B2%D0%BE%D0%B4%D1%8B,%D0%9F%D1%80%D0%B8%D0%BB%D0%BE%D0%B6%D0%B5%D0%BD%D0%B8%D0%B5%20%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D0%B0%D0%B5%D1%82%20%D0%B2%D0%BD%D1%83%D1%82%D1%80%D0%B8%20%D0%BA%D0%BE%D0%BD%D1%82%D0%B5%D0%B9%D0%BD%D0%B5%D1%80%D0%B0%20Docker!) 79 | 80 | ## README.md 81 | 82 | - eng [English](https://github.com/lumorow/golang-interview-preparation/blob/main/Docker/README.md) 83 | - ru [Русский](https://github.com/lumorow/golang-interview-preparation/blob/main/Docker/readme/README.ru.md) -------------------------------------------------------------------------------- /Docker/readme/README.ru.md: -------------------------------------------------------------------------------- 1 | # Docker 2 | Docker — инструмент для сборки пакетов, поставки и запуска приложений в «контейнерах» 3 | 4 | ## Что такое контейнер Docker? 5 | 6 | Контейнер — базовая единица программного обеспечения, покрывающая код и все его зависимости 7 | для обеспечения запуска приложения прозрачно, быстро и надежно независимо от окружения. Контейнер 8 | Docker может быть создан с использованием образа Docker. Это исполняемый пакет программного обеспечения, 9 | содержащий все необходимое для запуска приложения, например, системные программы, библиотеки, код, среды исполнения 10 | и настройки. 11 | 12 | ## Cоставные части архитектуры Docker 13 | 14 | Основные составные части архитектуры Docker — это: 15 | 16 | - `сервер`, содержит сервис Docker, образы и контейнеры. Сервис связывается с `Registry`, 17 | образы — метаданные приложений, запускаемых в контейнерах Docker. 18 | - `клиент`, применяется для запуска различных действий на сервере Docker. 19 | - `registry`, используется для хранения образов. Есть публичные, доступные каждому, например, `Docker Hub` и `Docker Cloud`. 20 | 21 | ## Наиболее важные команды Docker 22 | 23 | Наиболее важные команды Docker: 24 | - `build`, сборка образа для Docker 25 | - `create`, создание нового контейнера 26 | - `kill`. принудительная остановка контейнера 27 | - `dockerd`, запуск сервиса Docker 28 | - `commit`, создание нового образа из изменений в контейнере 29 | 30 | ## Состояние контейнера Docker 31 | 32 | Чтобы определить состояние, надо запустить команду: 33 | 34 | > docker ps -a 35 | 36 | Эта команда выведет список всех доступных контейнеров с их состоянием на сервере. 37 | Из этого списка нужно выбрать требуемый контейнер и узнать его состояние. 38 | 39 | ## Образ Docker, Docker run 40 | 41 | Образ Docker — это набор файлов, соединенный с настройками, с помощью которого можно создать экземпляры, 42 | которые запускаются в отдельных контейнерах в виде изолированных процессов. Образ строится с использованием 43 | инструкций для получения полной исполняемой версии приложения, зависящей от версии ядра сервера. 44 | Команда `Docker run` используется для создания таких экземпляров, называемых контейнерами, запускаемыми 45 | с использованием образов Docker. При запуске одного образа пользователь может создать несколько контейнеров. 46 | 47 | ## Различия между виртуализацией и контейнеризацией 48 | 49 | `Виртуализация` позволяет запустить несколько операционных систем на одном физическом сервере. 50 | `Контейнеризация` работает на одной и той же операционной системе, в которой приложения упакованы 51 | в контейнеры и запускаются на одном сервере/виртуальной машине. 52 | 53 | ## Продвинутые команды Docker 54 | 55 | Наиболее важные из них: 56 | 57 | - `docker -version`: узнать установленную версию Docker; 58 | - `docker ps`: перечислить все запущенные контейнеры вместе с дополнительной информацией о них; 59 | - `docker ps -a`: перечислить все контейнеры, включая остановленные, вместе с дополнительной информацией о них; 60 | - `docker exec`: войти в контейнер и выполнить в нем команду; 61 | - `docker build`: собрать образ из Dockerfile; 62 | - `docker rm`: удалить контейнер с указанным идентификатором; 63 | - `docker rmi`: удалить образ с указанным идентификатором; 64 | - `docker info`: получить расширенную информацию об установленном Docker, например, сколько запущено контейнеров, образов, версию ядра, доступную оперативную память и т.п.; 65 | - `docker cp`: сохранить файл из контейнера в локальную систему; 66 | - `docker history`: показать историю образа с указанным именем. 67 | 68 | ## Docker и Docker Compose 69 | 70 | Docker применяется для управления отдельными контейнерами (сервисами), из которых состоит приложение. 71 | 72 | Docker Compose используется для одновременного управления несколькими контейнерами, входящими в состав приложения. 73 | Этот инструмент предлагает те же возможности, что и Docker, но позволяет работать с более сложными приложениями. 74 | 75 | ## Дополнительный материал 76 | 77 | - [50 вопросов по Docker](https://habr.com/ru/companies/slurm/articles/528206/) 78 | - [20 распространенных вопросов про Docker на собеседовании](https://itsecforu.ru/2020/01/15/%F0%9F%90%B3-20-%D1%80%D0%B0%D1%81%D0%BF%D1%80%D0%BE%D1%81%D1%82%D1%80%D0%B0%D0%BD%D0%B5%D0%BD%D0%BD%D1%8B%D1%85-%D0%B2%D0%BE%D0%BF%D1%80%D0%BE%D1%81%D0%BE%D0%B2-%D0%BF%D1%80%D0%BE-docker-%D0%BD%D0%B0/) 79 | - [Руководство по Docker](https://medium.com/nuances-of-programming/%D1%80%D1%83%D0%BA%D0%BE%D0%B2%D0%BE%D0%B4%D1%81%D1%82%D0%B2%D0%BE-%D0%BF%D0%BE-docker-%D1%87%D0%B0%D1%81%D1%82%D1%8C-1-%D0%BE%D0%B1%D1%80%D0%B0%D0%B7-%D0%BA%D0%BE%D0%BD%D1%82%D0%B5%D0%B9%D0%BD%D0%B5%D1%80-%D1%81%D0%BE%D0%BF%D0%BE%D1%81%D1%82%D0%B0%D0%B2%D0%BB%D0%B5%D0%BD%D0%B8%D0%B5-%D0%BF%D0%BE%D1%80%D1%82%D0%BE%D0%B2-%D0%B8-%D0%BE%D1%81%D0%BD%D0%BE%D0%B2%D0%BD%D1%8B%D0%B5-%D0%BA%D0%BE%D0%BC%D0%B0%D0%BD%D0%B4%D1%8B-4997f2968925#:~:text=%D0%BD%D0%B0%D1%81%D1%82%D1%80%D0%BE%D0%B5%D0%BD%D0%BD%D0%BE%D0%B5%20%D1%81%D0%BE%D0%BF%D0%BE%D1%81%D1%82%D0%B0%D0%B2%D0%BB%D0%B5%D0%BD%D0%B8%D0%B5%20%D0%BF%D0%BE%D1%80%D1%82%D0%BE%D0%B2-,%D0%92%D1%8B%D0%B2%D0%BE%D0%B4%D1%8B,%D0%9F%D1%80%D0%B8%D0%BB%D0%BE%D0%B6%D0%B5%D0%BD%D0%B8%D0%B5%20%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D0%B0%D0%B5%D1%82%20%D0%B2%D0%BD%D1%83%D1%82%D1%80%D0%B8%20%D0%BA%D0%BE%D0%BD%D1%82%D0%B5%D0%B9%D0%BD%D0%B5%D1%80%D0%B0%20Docker!) 80 | 81 | ## README.md 82 | 83 | - eng [English](https://github.com/lumorow/golang-interview-preparation/blob/main/Docker/README.md) 84 | - ru [Русский](https://github.com/lumorow/golang-interview-preparation/blob/main/Docker/readme/README.ru.md) -------------------------------------------------------------------------------- /Kafka/README.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lumorow/golang-interview-preparation/776f95d5080a09bec52af0b5d0defc3a55529add/Kafka/README.md -------------------------------------------------------------------------------- /Kafka/readme/README.ru.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lumorow/golang-interview-preparation/776f95d5080a09bec52af0b5d0defc3a55529add/Kafka/readme/README.ru.md -------------------------------------------------------------------------------- /Multithreading/README.md: -------------------------------------------------------------------------------- 1 | # Multithreading golang 2 | 3 |

4 | 5 | Executing more than one task at the same time is known as multithreading. Go is rich in functionality 6 | for working with multithreading, in particular, tools such as goroutines and channels. 7 | 8 | ## Goroutines 9 | *** 10 | 11 | Goroutines are “lightweight threads” and serve to potentially parallelize the work of a program. 12 | A goroutine stack initially weighs only `2 KB` and can dynamically expand or shrink depending on needs. 13 | 14 | Stack size, we can find it in `runtime/stack.go`: 15 | ```golang 16 | // The minimum size of stack used by Go code 17 | _StackMin = 2048 18 | ``` 19 | If there are several goroutines, then it is impossible to say exactly in what order they will 20 | be executed, so the scheduler is responsible for this. 21 | 22 | ## Channel 23 | *** 24 | 25 | Channels are used for communication and data transfer through goroutines and their synchronization. 26 | A channel can be both reading and sending. 27 | ```golang 28 | ch := make(chan type) 29 | ch <- "hello" // Write to channel 30 | tmp := <- ch // Read from the channel 31 | close(ch) // Close the channel 32 | ``` 33 | 34 | With `make(chan type)` a structure with 10 fields is created, and 4 of them will be parsed. 35 | ```golang 36 | type hchan struct { 37 | qcount uint // total data in the queue 38 | dataqsiz uint // size of the circular queue 39 | buf unsafe.Pointer // points to an array of dataqsiz elements 40 | elemsize uint16 41 | closed uint32 42 | elemtype *_type // element type 43 | sendx uint // send index 44 | recvx uint // receive index 45 | recvq waitq // list of recv waiters 46 | sendq waitq // list of send waiters 47 | 48 | // lock protects all fields in hchan, as well as several 49 | // fields in sudogs blocked on this channel. 50 | // 51 | // Do not change another G's status while holding this lock 52 | // (in particular, do not ready a G), as this can deadlock 53 | // with stack shrinking. 54 | lock mutex 55 | } 56 | ``` 57 | 58 | The first, `buf` - `Ring buffer` (`circle queue`), which stores our data. 59 | Typically, the implementation of a circular queue is done on an array and on two pointers (indexes) in this array: 60 | We constantly write and increment one index, and we read and increment the other index (`sendx` and `recvx`). 61 | And when we reach the end, we simply move to the beginning. Here we have an array and two indexes, 62 | on which we write and read. And there is also `lock`. 63 | In the case when we have a full buffer and cannot write, a queue of goroutines begins to form. 64 | 65 | ### Unbuffered channels 66 | *** 67 | Unbuffered channels can only transmit one piece of data at a time, with blocking. 68 | 69 | When a goroutine (gopher) sends data to a channel, it blocks until another goroutine reads the data from the channel. 70 | Similar to blocking when writing to a channel, a goroutine can block when reading from a channel until nothing is written to it. 71 | ```golang 72 | ch := make(chan string) 73 | ``` 74 | 75 | ### Buffered channels 76 | *** 77 | 78 | We can send multiple pieces of data into a buffered channel without having to be read by another goroutine. 79 | This is the main difference from unbuffered channels. 80 | ```golang 81 | ch := make(chan string, 5) 82 | ``` 83 | 84 | ## Reading from a channel 85 | *** 86 | ### - In a for-range loop 87 | 88 | ```golang 89 | go func() { 90 | for data := range сh { 91 | fmt.Println(data) 92 | } 93 | }() 94 | ``` 95 | Once all data from the channel has been processed, the loop will block on reading; 96 | To avoid blocking, you need to close the channel by calling `close(ch)`. 97 | 98 | ### - Non-blocking read from channel 99 | By using the `select-case` construct, blocking reading from the pipe can be avoided. 100 | The goroutine will read data from the channel if it is there, otherwise the `default` block is executed: 101 | 102 | ```golang 103 | func main() { 104 | myChan := make(chan string) 105 | 106 | go func() { 107 | myChan <- "Message!" 108 | }() 109 | 110 | select { 111 | case msg := <-myChan: 112 | fmt.Println(msg) 113 | default: 114 | fmt.Println("No Msg") 115 | } 116 | <-time.After(time.Second * 1) 117 | select { 118 | case msg := <-myChan: 119 | fmt.Println(msg) 120 | default: 121 | fmt.Println("No Msg") 122 | } 123 | } 124 | ``` 125 | 126 | Once run, this code will output the following: 127 | >No Msg 128 | Message! 129 | 130 | ## Recording in a channel 131 | *** 132 | ### - Non-blocking channel recording 133 | 134 | ```golang 135 | select { 136 | case myChan <- "message": 137 | fmt.Println("sent the message") 138 | default: 139 | fmt.Println("no message sent") 140 | } 141 | ``` 142 | 143 | ## Synchronization 144 | *** 145 | You can synchronize channels in the following ways (examples can be found in [mthreading.go](https://github.com/lumorow/golang-interview-preparation/blob/main/Multithreading/mthreading.go)) 146 | - WaitGroup 147 | - Context 148 | - Chan 149 | 150 | ## Deadlock 151 | 152 | > fatal error: all goroutines are asleep - deadlock! 153 | 154 |

155 | 156 | Deadlock is a mistake 157 | which occurs when processes have a cyclic dependence on a pair of synchronized objects. 158 | 159 | Deadlock is a program in which all parallel processes wait for each other. 160 | In this state, the program will never recover without outside intervention. 161 | 162 | ### Example 163 | ```golang 164 | func main() { 165 | var wg sync.WaitGroup 166 | printSum := func(v1, v2 *value) { 167 | defer wg.Done() 168 | 169 | v1.mu.Lock() // Process 1 is blocking A; Process 2 is blocking B 170 | defer v1.mu.Unlock() 171 | 172 | time.Sleep(2 * time.Second) 173 | 174 | v2.mu.Lock() // Process 1 is waiting for B; Process 2 is waiting for A 175 | defer v2.mu.Unlock() 176 | 177 | fmt.Printf("sum=%v\n", v1.value+v2.value) 178 | } 179 | var a, b value 180 | wg.Add(2) 181 | go printSum(&a, &b) // Process 1 182 | go printSum(&b, &a) // Process 2 183 | wg.Wait() 184 | } 185 | 186 | type value struct { 187 | mu sync.Mutex 188 | value int 189 | } 190 | ``` 191 | > fatal error: all goroutines are asleep — deadlock! 192 | 193 | Debugging deadlocks, like other synchronization errors, is complicated by the fact that 194 | for their occurrence, specific conditions for the simultaneous execution of several processes are required. 195 | If Process 1 had time to acquire resource B before Process 2, then the error would not have occurred. 196 | 197 | ## Race condition and Data Race 198 | 199 | Race condition and data race are two different multithreading problems that are often confused. Let's try to figure it out. 200 | 201 | ### Race condition 202 | Race condition is a flaw that occurs when the timing or order of events affects the correctness of the program. 203 | 204 | Given that race condition is a semantic error, there is no general way that can distinguish the correct one 205 | and incorrect program behavior in the general case. 206 | 207 | ### Data Race 208 | Data race is a condition when different threads access the same memory cell without any synchronization 209 | and at least one of the threads is writing. 210 | 211 | Data Races have a precise definition that is not necessarily related to correctness, and are therefore discoverable. 212 | There are many types of data race detectors (static/dynamic detection, 213 | lock-based detection, antecedent-based detection, hybrid data race detection). 214 | 215 | Go has a good [Data Race Detector](https://go.dev/doc/articles/race_detector) with which such 216 | errors can be detected. 217 | 218 | ## It is important to know 219 |

220 | 221 | ## Resources 222 | - [Изучаем многопоточное программирование в Go по картинкам](https://habr.com/ru/articles/412715/) 223 | - [Конкурентность в Go: пять примеров (МТС)](https://habr.com/ru/companies/ru_mts/articles/680324/) 224 | - [Go: как изменяется размер стека горутины?](https://habr.com/ru/companies/otus/articles/586108/) 225 | - [Go Channels Internals](https://habr.com/ru/companies/oleg-bunin/articles/522742/) 226 | - [Как на самом деле устроены каналы в Golang? | Golang channels internals (Николай Тузов — Golang)](https://www.youtube.com/watch?v=ZTJcaP4G4JM&ab_channel=%D0%9D%D0%B8%D0%BA%D0%BE%D0%BB%D0%B0%D0%B9%D0%A2%D1%83%D0%B7%D0%BE%D0%B2%E2%80%94Golang) 227 | - [Разбираемся с пакетом Context в Golang](https://habr.com/ru/companies/nixys/articles/461723/) 228 | 229 | ## README.md 230 | *** 231 | 232 | - eng [English](https://github.com/lumorow/golang-interview-preparation/blob/main/Multithreading/README.md) 233 | - ru [Русский](https://github.com/lumorow/golang-interview-preparation/blob/main/Multithreading/readme/README.ru.md) -------------------------------------------------------------------------------- /Multithreading/mthreading.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "time" 7 | ) 8 | 9 | ////**********************************************************************************************************************//// 10 | //// context.WithCancel(parent Context) (ctx Context, cancel CancelFunc) 11 | 12 | func readChan(ctx context.Context) { 13 | for { 14 | select { 15 | default: 16 | time.Sleep(200 * time.Millisecond) 17 | fmt.Println("I working...") 18 | case <-ctx.Done(): // Кейс сигнала отмены контекста 19 | fmt.Println("<<<>>>") 20 | return 21 | } 22 | } 23 | } 24 | 25 | func main() { 26 | ctx, cancelFunc := context.WithCancel(context.Background()) 27 | go readChan(ctx) 28 | time.Sleep(3 * time.Second) 29 | cancelFunc() // Вызываем функцию отмены контекста 30 | time.Sleep(1 * time.Second) 31 | fmt.Println("Program completion") 32 | } 33 | 34 | ////**********************************************************************************************************************//// 35 | //// ch <-chan bool 36 | 37 | //func readChan(ch <-chan bool) { 38 | // for { 39 | // select { 40 | // default: 41 | // time.Sleep(200 * time.Millisecond) 42 | // fmt.Println("I working...") 43 | // case <-ch: // Ожидаем сигнал от канала, для выхода из функции 44 | // fmt.Println("<<<>>>") 45 | // return 46 | // } 47 | // } 48 | //} 49 | // 50 | //func main() { 51 | // stopChan := make(chan bool) 52 | // go readChan(stopChan) 53 | // time.Sleep(3 * time.Second) 54 | // stopChan <- true // Посылаем сигнал в канал 55 | // close(stopChan) 56 | // fmt.Println("Program completion") 57 | //} 58 | 59 | //**********************************************************************************************************************//// 60 | // time.After(int * time.Second) 61 | 62 | //func readChan() { 63 | // to := time.After(3 * time.Second) 64 | // for { 65 | // select { 66 | // case <-to: 67 | // fmt.Println("<<<>>>") 68 | // return 69 | // default: 70 | // time.Sleep(200 * time.Millisecond) 71 | // fmt.Println("I working...") 72 | // } 73 | // } 74 | //} 75 | // 76 | //func main() { 77 | // go readChan() 78 | // time.Sleep(4 * time.Second) 79 | // fmt.Println("Program completion") 80 | //} 81 | 82 | ////**********************************************************************************************************************//// 83 | //// sync.WaitGroup для ожидания завершения главного потока 84 | 85 | //func readChan(id int, wg *sync.WaitGroup) { 86 | // fmt.Println(fmt.Sprintf("id: %d| I working...", id)) 87 | // time.Sleep(2 * time.Second) 88 | // fmt.Println(fmt.Sprintf("\"id: %d| <<<>>>", id)) 89 | // wg.Done() 90 | //} 91 | // 92 | //func main() { 93 | // var wg sync.WaitGroup 94 | // wg.Add(3) 95 | // for i := 0; i < 3; i++ { 96 | // go readChan(i, &wg) 97 | // } 98 | // wg.Wait() // Главный поток не завершится, пока не будет готова вся группа 99 | // fmt.Println("Program completion") 100 | //} 101 | 102 | ////**********************************************************************************************************************//// 103 | //// Используем os/signal 104 | 105 | //func readChan(sigCh <-chan os.Signal) { 106 | // for { 107 | // select { 108 | // case <-sigCh: // Кейс на сигнал (control + C) 109 | // fmt.Println("<<<>>>") 110 | // return 111 | // default: 112 | // time.Sleep(200 * time.Millisecond) 113 | // fmt.Println("I working...") 114 | // } 115 | // } 116 | //} 117 | // 118 | //func main() { 119 | // sigCh := make(chan os.Signal, 1) 120 | // signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM) 121 | // go readChan(sigCh) 122 | // <-sigCh // Ожидаем сигнал (control + C) 123 | // fmt.Println("Program completion") 124 | //} 125 | -------------------------------------------------------------------------------- /Multithreading/readme/README.ru.md: -------------------------------------------------------------------------------- 1 | # Многопоточность в golang 2 | 3 |

4 | 5 | Одновременное выполнение более чем одной задачи известно как многопоточность. Go имеет богатую функциональность 6 | для работы с многопоточностью, в частности, такие инструменты как горутины и каналы. 7 | 8 | ## Горутины 9 | *** 10 | 11 | Горутины - это «легковесные потоки» и служат для потенциального распараллеливания работы программы. 12 | Стек горутин изначально весит всего 2 КБ и может динамически расширяться или уменьшаться в зависимости от потребностей. 13 | 14 | Размера стека, мы можем найти его в runtime/stack.go: 15 | ```golang 16 | // The minimum size of stack used by Go code 17 | _StackMin = 2048 18 | ``` 19 | Если есть несколько горутин, то невозможно сказать точно, в каком порядке они выполнятся, так за это отвечает планировщик. 20 | 21 | ## Каналы 22 | *** 23 | 24 | Каналы служат для общения-передачи данных через горутины и их синхронизации. 25 | Канал может быть и читающим, и отправляющим. 26 | ```golang 27 | ch := make(chan type) 28 | ch <- "hello" // Записать в канал 29 | tmp := <- ch // Прочитать из канала 30 | close(ch) // Закрыть канал. 31 | ``` 32 | При `make(chan type)` создается структура с 10 полями, и 4 из них разберем. 33 | ```golang 34 | type hchan struct { 35 | qcount uint // total data in the queue 36 | dataqsiz uint // size of the circular queue 37 | buf unsafe.Pointer // points to an array of dataqsiz elements 38 | elemsize uint16 39 | closed uint32 40 | elemtype *_type // element type 41 | sendx uint // send index 42 | recvx uint // receive index 43 | recvq waitq // list of recv waiters 44 | sendq waitq // list of send waiters 45 | 46 | // lock protects all fields in hchan, as well as several 47 | // fields in sudogs blocked on this channel. 48 | // 49 | // Do not change another G's status while holding this lock 50 | // (in particular, do not ready a G), as this can deadlock 51 | // with stack shrinking. 52 | lock mutex 53 | } 54 | ``` 55 | 56 | Первое, `buf` — `Ring buffer` (`circle queue`, или кольцевая очередь), которое хранит наши данные. 57 | Обычно имплементация кольцевой очереди делается на массиве и на двух указателях (индексах) в этом массиве: 58 | один индекс мы постоянно пишем и инкрементируем, а другой индекс читаем и инкрементируем (`sendx` и `recvx`). 59 | И когда мы достигаем конца, то просто перемещаемся в начало. Здесь же у нас есть массив и два индекса, 60 | по которым пишем и читаем. И есть еще `lock`. 61 | В случае, когда у нас полный буфер и мы не можем писать, начинает выстраиваться очередь из горутин. 62 | 63 | ### Небуферизованные каналы 64 | *** 65 | В небуферизованные каналы можно передать только один фрагмент данных за раз, с блокировкой. 66 | 67 | Когда горутина (гофер) посылает данные в канал, она блокируется до тех пор, пока другая горутина не прочитает данные из канала. 68 | Аналогично блокировке при записи в канал, горутина может быть заблокирована при чтении из канала до тех пор, пока в него ничего не запишут. 69 | ```golang 70 | ch := make(chan string) 71 | ``` 72 | 73 | ### Буферизованные каналы 74 | *** 75 | 76 | В буферизоваванный канал мы можем послать несколько фрагментов данных, без необходимости чтения их другой горутиной. 77 | Это основное отличие от небуферизованных каналов. 78 | ```golang 79 | ch := make(chan string, 5) 80 | ``` 81 | 82 | ## Чтение из канала 83 | *** 84 | ### - В цикле for-range 85 | 86 | ```golang 87 | go func() { 88 | for data := range сh { 89 | fmt.Println(data) 90 | } 91 | }() 92 | ``` 93 | Как все данные из канала обработаны, цикл заблокируется на чтении; 94 | чтобы избежать блокировки, нужно закрыть канал вызовом `close(ch)`. 95 | 96 | ### - Неблокирующе чтение из канала 97 | Используя конструкцию `select-case`, можно избежать блокирующего чтения из канала. 98 | Горутина прочитает из канала данные, если только они там есть, в противном случае выполняется блок `default`: 99 | 100 | ```golang 101 | func main() { 102 | myChan := make(chan string) 103 | 104 | go func() { 105 | myChan <- "Message!" 106 | }() 107 | 108 | select { 109 | case msg := <-myChan: 110 | fmt.Println(msg) 111 | default: 112 | fmt.Println("No Msg") 113 | } 114 | <-time.After(time.Second * 1) 115 | select { 116 | case msg := <-myChan: 117 | fmt.Println(msg) 118 | default: 119 | fmt.Println("No Msg") 120 | } 121 | } 122 | ``` 123 | После запуска этот код выведет следующее: 124 | >No Msg 125 | Message! 126 | 127 | ## Запись в канал 128 | *** 129 | ### - Неблокирующая запись в канал 130 | 131 | ```golang 132 | select { 133 | case myChan <- "message": 134 | fmt.Println("sent the message") 135 | default: 136 | fmt.Println("no message sent") 137 | } 138 | ``` 139 | 140 | ## Синхронизация 141 | *** 142 | Синхронизировать каналы можно следующими способами (примеры можно найти в [mthreading.go](https://github.com/lumorow/golang-interview-preparation/blob/main/Multithreading/mthreading.go)) 143 | - WaitGroup 144 | - Context 145 | - Chan 146 | 147 | ## Deadlock 148 | 149 | > fatal error: all goroutines are asleep - deadlock! 150 | 151 |

152 | 153 | Deadlock или взаимная блокировка — это ошибка, 154 | которая происходит когда процессы имеют циклическую зависимость от пары синхронизированных объектов. 155 | 156 | Deadlock — это программа, в которой все параллельные процессы ожидают друг друга. 157 | В этом состоянии программа никогда не восстановится без вмешательства извне. 158 | 159 | ### Пример 160 | ```golang 161 | func main() { 162 | var wg sync.WaitGroup 163 | printSum := func(v1, v2 *value) { 164 | defer wg.Done() 165 | 166 | v1.mu.Lock() // Процесс 1 блокирует А; Процесс 2 блокирует B 167 | defer v1.mu.Unlock() 168 | 169 | time.Sleep(2 * time.Second) 170 | 171 | v2.mu.Lock() // Процесс 1 ожидает B; Процесс 2 ожидает А 172 | defer v2.mu.Unlock() 173 | 174 | fmt.Printf("sum=%v\n", v1.value+v2.value) 175 | } 176 | var a, b value 177 | wg.Add(2) 178 | go printSum(&a, &b) // Процесс 1 179 | go printSum(&b, &a) // Процесс 2 180 | wg.Wait() 181 | } 182 | 183 | type value struct { 184 | mu sync.Mutex 185 | value int 186 | } 187 | ``` 188 | > fatal error: all goroutines are asleep — deadlock! 189 | 190 | Отладка взаимных блокировок, как и других ошибок синхронизации, усложняется тем, 191 | что для их возникновения нужны специфические условия одновременного выполнения нескольких процессов. 192 | Если бы Процесс 1 успел захватить ресурс B до Процесса 2, то ошибка не произошла бы. 193 | 194 | ## Race condition и Data Race 195 | 196 | Race condition и data race — две разные проблемы многопоточности, которые часто путают. Попробуем разобраться. 197 | 198 | ### Race condition 199 | Race condition — это недостаток, возникающий, когда время или порядок событий влияют на правильность программы. 200 | 201 | Учитывая, что race condition семантическая ошибка, нет общего способа который может отличить правильное 202 | и неправильное поведение программы в общем случае. 203 | 204 | #### Data Race 205 | Data race это состояние когда разные потоки обращаются к одной ячейке памяти без какой-либо синхронизации 206 | и как минимум один из потоков осуществляет запись. 207 | 208 | У Data Race есть точное определение, которое необязательно связано с корректностью, и поэтому их можно обнаружить. 209 | Существует множество разновидностей детекторов гонки данных (статическое/динамическое обнаружение, обнаружение 210 | на основе блокировок, обнаружение основанное на предшествующих событий, обнаружение гибридного data race). 211 | 212 | У Go есть хороший [Data Race Detector](https://go.dev/doc/articles/race_detector) с помощью которого такие ошибки 213 | можно обнаружить. 214 | 215 | ## Важно знать 216 |

217 | 218 | ## Дополнительный материал 219 | - [Изучаем многопоточное программирование в Go по картинкам](https://habr.com/ru/articles/412715/) 220 | - [Конкурентность в Go: пять примеров (МТС)](https://habr.com/ru/companies/ru_mts/articles/680324/) 221 | - [Go: как изменяется размер стека горутины?](https://habr.com/ru/companies/otus/articles/586108/) 222 | - [Go Channels Internals](https://habr.com/ru/companies/oleg-bunin/articles/522742/) 223 | - [Как на самом деле устроены каналы в Golang? | Golang channels internals (Николай Тузов — Golang)](https://www.youtube.com/watch?v=ZTJcaP4G4JM&ab_channel=%D0%9D%D0%B8%D0%BA%D0%BE%D0%BB%D0%B0%D0%B9%D0%A2%D1%83%D0%B7%D0%BE%D0%B2%E2%80%94Golang) 224 | - [Разбираемся с пакетом Context в Golang](https://habr.com/ru/companies/nixys/articles/461723/) 225 | - [Race condition и Data Race](https://medium.com/german-gorelkin/race-8936927dba20) 226 | 227 | ## README.md 228 | *** 229 | 230 | - eng [English](https://github.com/lumorow/golang-interview-preparation/blob/main/Multithreading/README.md) 231 | - ru [Русский](https://github.com/lumorow/golang-interview-preparation/blob/main/Multithreading/readme/README.ru.md) -------------------------------------------------------------------------------- /Networking/README.md: -------------------------------------------------------------------------------- 1 | # Basic knowledge of networks 2 | 3 | ## REST API 4 | 5 | REST API is a way for websites and web applications to interact with the server. It is also called RESTful "architectural style". 6 | 7 |

8 | 9 | API (Application Programming Interface) is code that allows two applications to exchange 10 | data from the server. 11 | 12 | REST (Representational State Transfer) is a way of creating APIs using the HTTP protocol. 13 | 14 | *** 15 | ### REST API Principles 16 | RESTful has 7 principles for coding interfaces. 17 | 18 | - Separation of the client from the server (`Client-Server`). 19 | The client is the user interface of a site or application, for example, a video hosting search bar. 20 | In a REST API, the request code stays on the client side and the data access code stays on the server side. 21 | This simplifies the organization of the API and makes it easy to transfer the user interface to another platform 22 | and makes it possible to better scale server data storage. 23 | 24 | - Lack of client state recording (`Stateless`). The server should not store state information 25 | (operations performed) of the client. Each request from the client must contain only the information 26 | which is needed to receive data from the server. 27 | 28 | - Cacheable. The request data must indicate whether the data should be cached 29 | (save in a special buffer for frequent requests). If there is such an indication, the client will receive 30 | the right to access this buffer if necessary. 31 | 32 | - `Uniform Interface`. All data must be requested through one URL 33 | standard protocols such as HTTP. This simplifies the architecture of the site or application and makes 34 | interaction with the server is clearer. 35 | 36 | - Multi-level system (`Layered System`). In RESTful, servers can be located at different levels, 37 | Moreover, each server interacts only with the nearest levels and is not connected by requests with others. 38 | 39 | - Providing code upon request (`Code on Demand`). Servers can send code to the client 40 | (for example, a script to start a video). This way, the overall code of an application or website becomes more complex only when necessary. 41 | 42 | - `Starting with the Null Style`. The client knows only one entry point to the server. 43 | Further interaction opportunities are provided by the server. 44 | 45 | *** 46 | ### The REST API has 4 HTTP methods that are used to manipulate objects on servers: 47 | 48 | - GET (receiving information about data or a list of objects) 49 | - DELETE (deleting data) 50 | - POST (adding or replacing data) 51 | - PUT (regular data update) 52 | 53 | Such requests are also called `CRUD` identifiers: create (create), read (read), update (update) delete (delete). 54 | This is a standard set of actions for working with data. 55 | 56 | ## TCP and UDP. In which case is UDP preferable? 57 | *** 58 | `TCP` is a transport protocol for data transfer in `TCP/IP` networks, which preliminarily establishes a connection to the network. 59 | `UDP` is a transport protocol that transmits datagram messages without the need to establish a connection in the `IP` network. 60 | 61 | The difference between the `TCP` and `UDP` protocols is the so-called “delivery guarantee”. `TCP` requires a response from the client, 62 | to whom the data packet is delivered, confirmation of delivery, and for this it needs a pre-established connection. 63 | Also, the `TCP` protocol is considered reliable, while `UDP` has even received the name “unreliable datagram protocol”. 64 | `TCP` eliminates data loss, duplication and mixing of packets, and delays. `UDP` allows all this, and the connection 65 | it doesn't need it to work. Processes to which data is sent via `UDP` must make do with what they receive, 66 | even with losses. `TCP` controls the congestion of the connection, `UDP` does not control anything except the integrity of received 67 | datagram. 68 | On the other hand, thanks to such non-selectivity and lack of control, `UDP` delivers data packets (datagrams) 69 | much faster, therefore for applications that are designed for high bandwidth and fast exchange, 70 | `UDP` can be considered the optimal protocol. These include online and browser games, as well as viewing programs 71 | streaming video and applications for video communication (or voice): the loss of a packet, complete or partial, does not change anything, 72 | It is not necessary to repeat the request, but the download is much faster. The `TCP` protocol, as more reliable, 73 | successfully used even in email programs, allowing you to control not only traffic, but also the length of the message 74 | and traffic exchange speed. 75 | 76 | ## What is NAT? 77 | *** 78 | Networks are usually designed using private `IP` addresses. 79 | These addresses are `10.0.0.0/8`, `172.16.0.0/12` and `192.168.0.0/16`. These private addresses are used within an organization or site, 80 | to allow devices to communicate locally and not be routed over the internet. To allow the device to 81 | private `IPv4` address to access devices and resources outside the local network, the private address must first 82 | be transferred to a publicly accessible address. 83 | 84 | And just `NAT` converts private addresses into public ones. This allows a device with a private `IPv4` address 85 | access resources outside of his private network. `NAT` in combination with `IPv4` private addresses has proven useful 86 | method of storing public `IPv4` addresses. One public `IPv4` address can be used by hundreds, even 87 | thousands of devices, each with a private `IPv4` address. `NAT` has the added benefit of 88 | in adding a degree of privacy and security to the network as it hides internal `IPv4` addresses from external ones 89 | networks. 90 | 91 | ## What are HTTP and HTTPS, what are their differences? 92 | *** 93 | `HTTP` (from the English HyperText Transfer Protocol - hypertext transfer protocol) is an application data transfer protocol 94 | online. Currently used to obtain information from websites. The `HTTP` protocol is based on the use 95 | “client-server” technologies: the client sending the request is the initiator of the connection; the server receiving the request 96 | executes it and sends the result to the client. 97 | 98 | `HTTPS` (from the English HyperText Transfer Protocol Secure - secure hypertext transfer protocol) is an extension 99 | `HTTP` protocol, supporting encryption using `SSL` and `TLS` cryptographic protocols. 100 | ### What is the difference between HTTP and HTTPS: 101 | 102 | `HTTPS` is not a separate data transfer protocol, but is an extension of the `HTTP` protocol with an encryption add-on; 103 | data transmitted via the `HTTP` protocol is not protected, `HTTPS` ensures the confidentiality of information by encrypting it; 104 | `HTTP` uses port 80, `HTTPS` uses port 443. 105 | 106 | ## What are SSL and TLS, are there any differences between them? 107 | *** 108 | `SSL` or Secure Sockets Layer was the original name of the protocol developed by `Netscape` 109 | in the mid-90s. SSL 1.0 was never publicly available, and version 2.0 had serious flaws. 110 | The `SSL 3.0` protocol, released in 1996, was completely redesigned and set the tone for the next stage of development. 111 | 112 | When the next version of the protocol was released in 1999, it was standardized by a special design working group 113 | network of the Internet and gave it a new name: transport layer security, or `TLS`. As the `TLS` documentation says, 114 | “the difference between this protocol and S`SL 3.0` is not critical.” `TLS` and `SSL` form a constantly updated series of protocols, 115 | and they are often combined under the name `SSL`/`TLS`. 116 | The `TLS` protocol encrypts Internet traffic of any kind. The most common type is web traffic. You know when your browser establishes a TLS connection - 117 | if the link in the address bar starts with "https". 118 | `TLS` is also used by other applications, such as mail and teleconferencing systems. 119 | The most secure encryption method is asymmetric encryption. This requires 2 keys, 1 public and 1 private. These are files with information, 120 | most often very large numbers. The mechanism is complex, but simply put, you can use a public key to encrypt data, but you need a private key to decrypt it. 121 | The two keys are linked using a complex mathematical formula that is difficult to hack. 122 | Because asymmetric encryption uses complex mathematical calculations, it requires a lot of computing resources. `TLS` solves this problem 123 | by using asymmetric encryption only at the beginning of the session to encrypt communications between the server and client. 124 | The server and client must agree on a single session key, which the two of them will use to encrypt data packets. 125 | 126 | ## OSI levels 127 | 128 | OSI model - describes how network devices work. This is a data transfer process that is divided into 7 levels. 129 | 130 | The process of data transfer always involves the sending device, the receiving device, as well as the data itself, 131 | which must be sent and received. From the point of view of an ordinary user, the task is elementary - you need to take 132 | and send this data. Everything that happens when sending and receiving data is described in detail by the seven-layer OSI model. 133 | *** 134 | ### L1, physical layer 135 | 136 | This layer works with cables, contacts in connectors, signal modulation, coding of ones and zeros and others 137 | low level things. 138 | Essentially, the first level is the level of wires and physical methods of signal transmission. Minimal abstraction. 139 | 140 | The most famous protocol at the physical layer is Ethernet. It describes how signals are encoded and transmitted over wires. 141 | In addition, there is Bluetooth, Wi-Fi and an infrared port, which also contain instructions for transferring data. 142 | 143 | Physical layer devices - hubs and repeaters. They work with the physical signal “stupidly” and do not delve into its logic: they received the data and transmitted it further along the wire. 144 | *** 145 | ### L2, data link layer 146 | 147 | Above the physical layer is the channel layer. Its task is to check the integrity of the received data and correct errors. 148 | This level is “smarter” than the previous one: it already understands that different voltage amplitudes correspond to different bits - zeros and 149 | units. The channel layer can also encode signals into bits and transmit them further. 150 | 151 | The data received from the lower level is divided into frames, or frames. Each frame consists of service information - for example, 152 | sender and recipient addresses, as well as the data itself. 153 | 154 | It turns out something like a postal envelope. On the front side it says who the letter came from, and inside 155 | the letter itself is located (in our case, data). 156 | 157 | The front side of the envelope is the MAC address of the device that sent us the information. It is needed to identify 158 | devices on the local network, consists of 48 or 64 bits and looks something like this: 159 | 160 | 161 | Another important fact about MAC addresses: when a laptop or smartphone is assembled at a factory, it is immediately assigned 162 | a specific MAC address, which then cannot be changed in any way. The MAC address of desktop PCs is hardwired into the network card, 163 | therefore, it can only be changed by replacing this very card. 164 | *** 165 | ### L3, network layer 166 | 167 | This layer is responsible for routing data within the network between computers. 168 | Terms such as “routers” and “IP addresses” already appear here. 169 | 170 | Routers allow different networks to communicate with each other: they use MAC addresses to build 171 | path from one device to another. 172 | 173 | Data at the network layer is represented in the form of packets. Such packets are similar to frames from the link layer, 174 | but use different recipient and sender addresses - IP addresses. 175 | 176 | To obtain the IP address of both devices (sender and recipient), there is a protocol 177 | ARP (address resolution protocol). It can convert MAC to IP address and vice versa. 178 | *** 179 | ### L4, transport layer 180 | 181 | From the name it is clear that at this level data is transferred over the network. This is true. 182 | The two main protocols here are TCP and UDP. They are precisely responsible for how exactly the data will be transmitted. 183 | *** 184 | ### L5, session layer 185 | 186 | From this level and higher, the data already has a normal form - for example, the JPEG or MP3 files we are familiar with. 187 | The task of the network at these levels is to present information in a form understandable to humans and to make it so 188 | so that the user can somehow “touch” it. 189 | 190 | The session layer manages connections, or sessions. A typical example is a Skype or Zoom call. 191 | When you call another person, a connection is established between your computers, 192 | through which audio and video are transmitted. If such a connection is interrupted, your call will be interrupted. 193 | 194 | At the session level, it is very important that the connection is established and maintained correctly. 195 | That is, protocol mechanisms must check that both interlocutors have the necessary codecs and 196 | there is a signal between the devices. 197 | *** 198 | ### L6, presentation layer 199 | 200 | At this level, data formats are converted - their encoding and compression. 201 | For example, the received data can be turned into a GIF or MP4 file. The same thing happens 202 | and in reverse order: when a user sends a file to another person, the data is first converted 203 | into bits and compressed, and then transmitted to the transport layer. 204 | 205 | In addition to encoding and compression at the presentation level, data can be encrypted - if necessary, of course. 206 | *** 207 | ### L7, application layer 208 | 209 | The last layer of the OSI model is the application layer. It contains network services, 210 | which help you surf the Internet without any problems. 211 | 212 | The application layer is like a kind of graphical interface for the entire OSI model - with its 213 | with the help of the user interacts with other levels without even knowing it. This interface is called the network interface. 214 | 215 | The most popular network interfaces are HTTP, HTTPS, FTP and SMTP. 216 | And the “devices” here are already programs: Zoom, Telegram, browsers. 217 | *** 218 | ## Resources 219 | 220 | - [REST API](https://blog.skillfactory.ru/glossary/rest-api/) 221 | - [How the Web Works: A Primer for Newcomers to Web Development (or anyone, really)](https://www.freecodecamp.org/news/how-the-web-works-a-primer-for-newcomers-to-web-development-or-anyone-really-b4584e63585c#.7l3tokoh1) 222 | - [How the Web Works Part II: Client-Server Model & the Structure of a Web Application](https://medium.com/free-code-camp/how-the-web-works-part-ii-client-server-model-the-structure-of-a-web-application-735b4b6d76e3#.e6tmj8112) 223 | - [HTTP 1, 2 and 3 — easy](https://habr.com/ru/articles/739166/) 224 | - [HTTP/1.1 and HTTP/2](https://www.8host.com/blog/v-chem-raznica-mezhdu-http1-1-i-http2/#:~:text=%D0%92%20%D0%BE%D1%82%D0%BB%D0%B8%D1%87%D0%B8%D0%B5%20%D0%BE%D1%82%20HTTP%2F1.1%2C%20%D0%BA%D0%BE%D1%82%D0%BE%D1%80%D1%8B%D0%B9%20%D0%B4%D0%BE%D0%BB%D0%B6%D0%B5%D0%BD%20%D0%B8%D1%81%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D0%BD%D0%B5%D1%81%D0%BA%D0%BE%D0%BB%D1%8C%D0%BA%D0%BE%20%D1%81%D0%BE%D0%B5%D0%B4%D0%B8%D0%BD%D0%B5%D0%BD%D0%B8%D0%B9,%D0%B2%20%D0%BF%D1%80%D0%B8%D0%B2%D1%8B%D1%87%D0%BD%D0%BE%D0%BC%20%D1%84%D0%BE%D1%80%D0%BC%D0%B0%D1%82%D0%B5%20%D0%B7%D0%B0%D0%BF%D1%80%D0%BE%D1%81%2D%D0%BE%D1%82%D0%B2%D0%B5%D1%82.) 225 | - [A Simple Guide to the OSI Networking Model for Beginners](https://selectel.ru/blog/osi-for-beginners/) 226 | - [What is the OSI model and why is it needed: the dissecting layer cake of the Internet](https://skillbox.ru/media/code/chto-takoe-model-osi-i-zachem-ona-nuzhna-prepariruem-sloyenyy-pirog-interneta/) 227 | - [Context packet in Go](https://habr.com/ru/companies/pt/articles/764850/) 228 | 229 | ## README.md 230 | 231 | - eng [English](https://github.com/lumorow/golang-interview-preparation/blob/main/Networking/README.md) 232 | - ru [Русский](https://github.com/lumorow/golang-interview-preparation/blob/main/Networking/readme/README.ru.md) -------------------------------------------------------------------------------- /Networking/readme/README.ru.md: -------------------------------------------------------------------------------- 1 | # Базовые знания по сетям 2 | 3 | ## REST API 4 | 5 | REST API — это способ взаимодействия сайтов и веб-приложений с сервером. Его также называют RESTful «архитектурным стилем». 6 | 7 |

8 | 9 | API (Application Programming Interface) — это код, который позволяет двум приложениям обмениваться 10 | данными с сервера. На русском языке его принято называть программным интерфейсом приложения. 11 | 12 | REST (Representational State Transfer) — это способ создания API с помощью протокола HTTP. 13 | На русском его называют «передачей состояния представления». 14 | *** 15 | ### Принципы REST API 16 | У RESTful есть 7 принципов написания кода интерфейсов. 17 | 18 | - Отделение клиента от сервера (`Client-Server`). 19 | Клиент — это пользовательский интерфейс сайта или приложения, например, поисковая строка видеохостинга. 20 | В REST API код запросов остается на стороне клиента, а код для доступа к данным — на стороне сервера. 21 | Это упрощает организацию API, позволяет легко переносить пользовательский интерфейс на другую платформу 22 | и дает возможность лучше масштабировать серверное хранение данных. 23 | 24 | - Отсутствие записи состояния клиента (`Stateless`). Сервер не должен хранить информацию о состоянии 25 | (проведенных операций) клиента. Каждый запрос от клиента должен содержать только ту информацию, 26 | которая нужна для получения данных от сервера. 27 | 28 | - Кэшируемость (`Casheable`). В данных запроса должно быть указано, нужно ли кэшировать данные 29 | (сохранять в специальном буфере для частых запросов). Если такое указание есть, клиент получит 30 | право обращаться к этому буферу при необходимости. 31 | 32 | - Единство интерфейса (`Uniform Interface`). Все данные должны запрашиваться через один URL-адрес 33 | стандартными протоколами, например, HTTP. Это упрощает архитектуру сайта или приложения и делает 34 | взаимодействие с сервером понятнее. 35 | 36 | - Многоуровневость системы (`Layered System`). В RESTful сервера могут располагаться на разных уровнях, 37 | при этом каждый сервер взаимодействует только с ближайшими уровнями и не связан запросами с другими. 38 | 39 | - Предоставление кода по запросу (`Code on Demand`). Серверы могут отправлять клиенту код 40 | (например, скрипт для запуска видео). Так общий код приложения или сайта становится сложнее только при необходимости. 41 | 42 | - Начало от нуля (`Starting with the Null Style`). Клиент знает только одну точку входа на сервер. 43 | Дальнейшие возможности по взаимодействию обеспечиваются сервером. 44 | 45 | *** 46 | ### В REST API есть 4 метода HTTP, которые используют для действий с объектами на серверах: 47 | 48 | - GET (получение информации о данных или списка объектов) 49 | - DELETE (удаление данных) 50 | - POST (добавление или замена данных) 51 | - PUT (регулярное обновление данных) 52 | 53 | Такие запросы еще называют идентификаторами `CRUD`: create (создать), read (прочесть), update (обновить) delete (удалить). 54 | Это стандартный набор действий для работы с данными. 55 | 56 | ## TCP и UDP. В каком случае UDP предпочтительнее? 57 | 58 | `TCP` – транспортный протокол передачи данных в сетях `TCP/IP`, предварительно устанавливающий соединение с сетью. 59 | `UDP` – транспортный протокол, передающий сообщения-датаграммы без необходимости установки соединения в `IP`-сети. 60 | 61 | Разница между протоколами `TCP` и `UDP` – в так называемой "гарантии доставки". `TCP` требует отклика от клиента, 62 | которому доставлен пакет данных, подтверждения доставки, и для этого ему необходимо установленное заранее соединение. 63 | Также протокол `TCP` считается надежным, тогда как `UDP` получил даже именование “протокол ненадежных датаграмм. 64 | `TCP` исключает потери данных, дублирование и перемешивание пакетов, задержки. `UDP` все это допускает, и соединение 65 | для работы ему не требуется. Процессы, которым данные передаются по `UDP`, должны обходиться полученным, 66 | даже и с потерями. `TCP` контролирует загруженность соединения, `UDP` не контролирует ничего, кроме целостности полученных 67 | датаграмм. 68 | С другой стороны, благодаря такой не избирательности и бесконтрольности, `UDP` доставляет пакеты данных (датаграммы) 69 | гораздо быстрее, потому для приложений, которые рассчитаны на широкую пропускную способность и быстрый обмен, 70 | `UDP` можно считать оптимальным протоколом. К таковым относятся сетевые и браузерные игры, а также программы просмотра 71 | потокового видео и приложения для видеосвязи (или голосовой): от потери пакета, полной или частичной, ничего не меняется, 72 | повторять запрос не обязательно, зато загрузка происходит намного быстрее. Протокол `TCP`, как более надежный, 73 | с успехом применяется даже в почтовых программах, позволяя контролировать не только трафик, но и длину сообщения 74 | и скорость обмена трафиком. 75 | 76 | ## Что такое NAT? 77 | *** 78 | Сети обычно проектируются с использованием частных `IP` адресов. 79 | Это адреса `10.0.0.0/8`, `172.16.0.0/12` и `192.168.0.0/16`. Эти частные адреса используются внутри организации или площадки, 80 | чтобы позволить устройствам общаться локально, и они не маршрутизируются в интернете. Чтобы позволить устройству с 81 | приватным `IPv4`-адресом обращаться к устройствам и ресурсам за пределами локальной сети, приватный адрес сначала должен 82 | быть переведен на общедоступный публичный адрес. 83 | 84 | И вот как раз `NAT` переводит приватные адреса, в общедоступные. Это позволяет устройству с частным адресом `IPv4` 85 | обращаться к ресурсам за пределами его частной сети. `NAT` в сочетании с частными адресами `IPv4` оказался полезным 86 | методом сохранения общедоступных `IPv4`-адресов. Один общедоступный `IPv4`-адрес может быть использован сотнями, даже 87 | тысячами устройств, каждый из которых имеет частный `IPv4`-адрес. `NAT` имеет дополнительное преимущество, заключающееся 88 | в добавлении степени конфиденциальности и безопасности в сеть, поскольку он скрывает внутренние `IPv4`-адреса из внешних 89 | сетей. 90 | 91 | ## Что такое HTTP и HTTPS, в чем их отличия? 92 | *** 93 | `HTTP` (от англ. HyperText Transfer Protocol — протокол передачи гипертекста) — это прикладной протокол передачи данных 94 | в сети. На текущий момент используется для получения информации с веб-сайтов. Протокол `HTTP` основан на использовании 95 | технологии «клиент-сервер»: клиент, отправляющий запрос, является инициатором соединения; сервер, получающий запрос, 96 | выполняет его и отправляет клиенту результат. 97 | 98 | `HTTPS` (от англ. HyperText Transfer Protocol Secure — безопасный протокол передачи гипертекста) — это расширение 99 | протокола `HTTP`, поддерживающее шифрование посредством криптографических протоколов `SSL` и `TLS`. 100 | 101 | ### Чем отличаются HTTP от HTTPS: 102 | 103 | `HTTPS` не является отдельным протоколом передачи данных, а представляет собой расширение протокола `HTTP` с надстройкой шифрования; 104 | передаваемые по протоколу `HTTP` данные не защищены, `HTTPS` обеспечивает конфиденциальность информации путем ее шифрования; 105 | `HTTP` использует порт 80, `HTTPS` — порт 443. 106 | 107 | ## Что такое SSL и TLS, есть ли между ними отличия? 108 | *** 109 | `SSL` или слой защищенных сокетов было оригинальным названием протокола, который разработала компания `Netscape` 110 | в середине 90-х. SSL 1.0 никогда не был публично доступным, а в версии 2.0 были серьезные недостатки. 111 | Протокол `SSL 3.0`, выпущенный в 1996, был полностью переделан и задал тон следующей стадии развития. 112 | 113 | Когда следующую версию протокола выпустили в 1999, ее стандартизировала специальная рабочая группа проектирования 114 | сети Интернет и дала ей новое название: защита транспортного уровня, или `TLS`. Как говорится в `TLS`-документации, 115 | «разница между этим протоколом и S`SL 3.0` не критичная». `TLS` и `SSL` формируют постоянно обновляемую серию протоколов, 116 | и их часто объединяют под названием `SSL`/`TLS`. 117 | Протокол `TLS` шифрует интернет-трафик любого вида. Самый распространенный вид — веб-трафик. Вы знаете, когда ваш браузер устанавливает соединение по TLS — если ссылка в адресной строке начинается с «https». 118 | `TLS` также используется другими приложениями — например, в почте и системах телеконференций. 119 | Самый безопасный метод шифрования — это асимметричное шифрование. Для этого требуется 2 ключа, 1 публичный и 1 приватный. Это файлы с информацией, чаще всего очень большие числа. Механизм сложный, но если попросту, вы можете использовать публичный ключ, чтобы шифровать данные, но вам нужен приватный ключ, чтобы расшифровывать их. Два ключа связаны с помощью сложной математической формулы, которую сложно хакнуть. 120 | Так как в асимметричном шифровании применяются сложные математические расчеты, нужно много вычислительных ресурсов. `TLS` решает эту проблему, используя асимметричное шифрование только в начале сессии, чтобы зашифровать общение между сервером и клиентом. Сервер и клиент должны договориться об одном ключе сессии, который они будут вдвоем использовать, чтобы зашифровать пакеты данных. 121 | 122 | ## Уровни OSI 123 | 124 | Модель OSI - описывает, как работают сетевые устройства. Это процесс передачи данных, котроые разделили на 7 уровней. 125 | 126 | В процессе передачи данных всегда участвуют устройство-отправитель, устройство-получатель, а также сами данные, 127 | которые должны быть переданы и получены. С точки зрения рядового пользователя задача элементарна — нужно взять 128 | и отправить эти данные. Все, что происходит при отправке и приеме данных, детально описывает семиуровневая модель OSI. 129 | *** 130 | ### 1-й уровень OSI — физический 131 | 132 | Этот слой работает с кабелями, контактами в разъёмах, модуляцией сигнала, кодированием единиц и нулей и другими 133 | низкоуровневыми штуками. 134 | По сути, первый уровень — это уровень проводов и физических способов передачи сигнала. Минимальная абстракция. 135 | 136 | Самый известный протокол на физическом уровне — Ethernet. Он описывает, как сигналы кодируются и передаются по проводам. 137 | Кроме него есть Bluetooth, Wi-Fi и ИК-порт, которые также содержат инструкции для передачи данных. 138 | 139 | Устройства физического уровня — концентраторы и репитеры. Они работают с физическим сигналом «втупую» и не вникают в его логику: получили данные — передали их дальше по проводу. 140 | *** 141 | ### 2-й уровень OSI — канальный 142 | 143 | Над физическим уровнем располагается канальный. Его задача — проверить целостность полученных данных и исправить ошибки. 144 | Этот уровень «поумнее» предыдущего: он уже понимает, что разные амплитуды напряжений отвечают разным битам — нулям и 145 | единицам. А ещё канальный уровень умеет кодировать сигналы в биты и передавать их дальше. 146 | 147 | Полученные с нижнего уровня данные делятся на фреймы, или кадры. Каждый фрейм состоит из служебной информации — например, 148 | адреса отправителя и адреса получателя, — а также самих данных. 149 | 150 | Получается что-то вроде почтового конверта. На лицевой стороне у него написано, от кого пришло письмо, а внутри 151 | находится само письмо (в нашем случае данные). 152 | 153 | Лицевая сторона конверта — это MAC-адрес устройства, которое отправило нам информацию. Он нужен, чтобы идентифицировать 154 | устройства в локальной сети, состоит из 48 или 64 бит и выглядит примерно так: 155 | 156 | 157 | Ещё один важный факт о MAC-адресах: когда на заводе собирают ноутбук или смартфон, ему сразу же присваивают 158 | определённый MAC-адрес, который потом уже никак нельзя поменять. MAC-адрес настольных ПК зашит в сетевую карту, 159 | поэтому его можно изменить, только заменив эту самую карту. 160 | *** 161 | ### 3-й уровень OSI — сетевой 162 | 163 | Этот уровень отвечает за маршрутизацию данных внутри сети между компьютерами. 164 | Здесь уже появляются такие термины, как «маршрутизаторы» и «IP-адреса». 165 | 166 | Маршрутизаторы позволяют разным сетям общаться друг с другом: они используют MAC-адреса, чтобы построить 167 | путь от одного устройства к другому. 168 | 169 | Данные на сетевом уровне представляются в виде пакетов. Такие пакеты похожи на фреймы из канального уровня, 170 | но используют другие адреса получателя и отправителя — IP-адреса. 171 | 172 | Чтобы получить IP-адрес обоих устройств (отправителя и получателя), существует протокол 173 | ARP (address resolution protocol). Он умеет конвертировать MAC- в IP-адрес и наоборот. 174 | *** 175 | ### 4-й уровень OSI — транспортный 176 | 177 | Из названия понятно, что на этом уровне происходит передача данных по сети. Так и есть. 178 | Два главных протокола здесь — TCP и UDP. Они как раз и отвечают за то, как именно будут передаваться данные. 179 | *** 180 | ### 5-й уровень OSI — сеансовый 181 | 182 | Начиная с этого уровня и выше, данные имеют уже нормальный вид — например, привычных нам JPEG- или MP3-файлов. 183 | Задача сети на этих уровнях — представить информацию в понятном для человека виде и сделать так, 184 | чтобы пользователь мог её как-то «потрогать». 185 | 186 | Сеансовый уровень управляет соединениями, или сессиями. Типичный пример — звонок по Skype или Zoom. 187 | Когда вы звоните другому человеку, между вашими компьютерами устанавливается соединение, 188 | по которому передаются аудио и видео. Если такое соединение разорвать, то и ваш звонок прервётся. 189 | 190 | На сеансовом уровне очень важно, чтобы соединение правильно установилось и поддерживалось. 191 | То есть механизмы протоколов должны проверить, что у обоих собеседников есть нужные кодеки и 192 | сигнал между устройствами присутствует. 193 | *** 194 | ### 6-й уровень OSI — уровень представления данных 195 | 196 | На этом уровне происходит преобразование форматов данных — их кодирование и сжатие. 197 | Например, полученные данные могут превратиться в GIF- или MP4-файл. То же самое происходит 198 | и в обратном порядке: когда пользователь отправляет файл другому человеку, данные сначала конвертируются 199 | в биты и сжимаются, а потом уже передаются на транспортный уровень. 200 | 201 | Помимо кодировки и сжатия на уровне представления, данные могут шифроваться — если, конечно, это необходимо. 202 | *** 203 | ### 7-й уровень OSI — прикладной 204 | 205 | Последний уровень модели OSI — прикладной. На нём находятся сетевые службы, 206 | которые помогают без проблем сёрфить в интернете. 207 | 208 | Прикладной уровень похож на некий графический интерфейс для всей модели OSI — с его 209 | помощью пользователь взаимодействует с другими уровнями, даже не подозревая об этом. Этот интерфейс называется сетевым. 210 | 211 | Самые популярные из сетевых интерфейсов — это HTTP, HTTPS, FTP и SMTP. 212 | А «устройства» здесь — это уже программы: Zoom, Telegram, браузеры. 213 | *** 214 | ## Дополнительный материал 215 | 216 | - [REST API](https://blog.skillfactory.ru/glossary/rest-api/) 217 | - [How the Web Works: A Primer for Newcomers to Web Development (or anyone, really)](https://www.freecodecamp.org/news/how-the-web-works-a-primer-for-newcomers-to-web-development-or-anyone-really-b4584e63585c#.7l3tokoh1) 218 | - [How the Web Works Part II: Client-Server Model & the Structure of a Web Application](https://medium.com/free-code-camp/how-the-web-works-part-ii-client-server-model-the-structure-of-a-web-application-735b4b6d76e3#.e6tmj8112) 219 | - [HTTP 1, 2 и 3 — просто](https://habr.com/ru/articles/739166/) 220 | - [HTTP/1.1 И HTTP/2](https://www.8host.com/blog/v-chem-raznica-mezhdu-http1-1-i-http2/#:~:text=%D0%92%20%D0%BE%D1%82%D0%BB%D0%B8%D1%87%D0%B8%D0%B5%20%D0%BE%D1%82%20HTTP%2F1.1%2C%20%D0%BA%D0%BE%D1%82%D0%BE%D1%80%D1%8B%D0%B9%20%D0%B4%D0%BE%D0%BB%D0%B6%D0%B5%D0%BD%20%D0%B8%D1%81%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D0%BD%D0%B5%D1%81%D0%BA%D0%BE%D0%BB%D1%8C%D0%BA%D0%BE%20%D1%81%D0%BE%D0%B5%D0%B4%D0%B8%D0%BD%D0%B5%D0%BD%D0%B8%D0%B9,%D0%B2%20%D0%BF%D1%80%D0%B8%D0%B2%D1%8B%D1%87%D0%BD%D0%BE%D0%BC%20%D1%84%D0%BE%D1%80%D0%BC%D0%B0%D1%82%D0%B5%20%D0%B7%D0%B0%D0%BF%D1%80%D0%BE%D1%81%2D%D0%BE%D1%82%D0%B2%D0%B5%D1%82.) 221 | - [Простое пособие по сетевой модели OSI для начинающих](https://selectel.ru/blog/osi-for-beginners/) 222 | - [Что такое модель OSI и зачем она нужна: препарируем слоёный пирог интернета](https://skillbox.ru/media/code/chto-takoe-model-osi-i-zachem-ona-nuzhna-prepariruem-sloyenyy-pirog-interneta/) 223 | - [Пакет context в Go: взгляд профессионала](https://habr.com/ru/companies/pt/articles/764850/) 224 | 225 | ## README.md 226 | 227 | - eng [English](https://github.com/lumorow/golang-interview-preparation/blob/main/Networking/README.md) 228 | - ru [Русский](https://github.com/lumorow/golang-interview-preparation/blob/main/Networking/readme/README.ru.md) -------------------------------------------------------------------------------- /OOP/README.md: -------------------------------------------------------------------------------- 1 | # Object Oriented Programming in golang 2 | 3 |

4 | 5 | ## Difference between new and make 6 | `make` allocates memory for reference data types (`slice`, `map`, `chan`) and also initializes 7 | their underlying data structures. 8 | 9 | `new` returns only pointers to the initialized memory and sets it to zero for type `T`, 10 | that is, `0` for `int`, `''` for `string` and `nil` for reference types (`slice`, `map`, `chan`) 11 | 12 | ## Class. Creating a Class Object 13 | 14 | In golang there are no such classes, but structures are used. Structures also have fields and methods, you can write 15 | its own constructor, but it will be represented as a regular method. 16 | 17 | ```golang 18 | type person struct { 19 | age int 20 | height int 21 | weight int 22 | male string 23 | name string 24 | } 25 | 26 | func NewPerson(age, height, weight int, male, name string) *person { 27 | return &person{ 28 | age: age, 29 | height: height, 30 | weight: weight, 31 | male: male, 32 | name: name, 33 | } 34 | } 35 | ``` 36 | 37 | ## Visibility of structure and fields 38 | `Go` uses the case rule of the first letter of the name - if the name begins with a capital letter - 39 | this is `public` access, if with lowercase it is `private`. 40 | From the example above we can see that our `person` structure is not exported (private), 41 | therefore it is only available in the given package where we initialized it. But we created a constructor, 42 | which can create this object for us according to the given instructions inside it. 43 | 44 | ## Implementation of concepts in golang: 45 | ### Inheritance 46 | 47 | Golang does not have inheritance, but uses `inlining`. 48 | The simplest use case for inheritance is that a child type must have access to the fields and methods of the parent type. 49 | This is done in Go through `inlining`. The base structure is embedded in the child structure, after which the base fields 50 | and methods can be directly accessed by the child structure. 51 | 52 | More details: 53 | [OOP: Inheritance in GOLANG complete guide](https://golangbyexample.com/oop-inheritance-golang-complete/) 54 | 55 | ### Polymorphism 56 | #### Compile Time Polymorphism - not possible in golang 57 | 58 | With compile-time polymorphism, the compiler decides which function to call. 59 | Examples of compile-time polymorphism would be: 60 | - method/function overloading: there is more than one method/function with the same name, 61 | but with different signatures or perhaps different return types; 62 | - operator overloading: the same operator is used to work with different data types. 63 | 64 | Go does not support method overloading. 65 | Go also does not support operator overloading. 66 | *** 67 | #### Run Time Polymorphism - achieved through interfaces 68 | 69 | Runtime polymorphism means that the decision about which function to call is made at runtime. 70 | In [oop.go](https://github.com/lumorow/golang-interview-preparation/blob/main/OOP/oop.go) `interface Grower` 71 | creates a contract with 72 | `person` and `dog` structures, which have different implementations of the `growUp()` function. 73 | 74 | More details: 75 | [OOP: Polymorphism in Go Complete Guide](https://golangbyexample.com/oop-polymorphism-in-go-complete-guide/) 76 | 77 | ### Abstract classes 78 | 79 | An interface in Go does not contain fields, nor does it allow you to define methods within it. Any type must implement all methods of an interface in order to have that interface's type. There are situations where it is useful to have a default method implementation as well as default fields in Go. Before we understand how this can be done, let's first understand the requirements for an abstract class: 80 | 81 | An abstract class must have default fields 82 | An abstract class must have a default method 83 | It should not be possible to directly instantiate an abstract class 84 | 85 | More details: 86 | [Abstract Class in GO: Complete Guide](https://golangbyexample.com/go-abstract-class/) 87 | 88 | ### Encapsulation 89 | 90 | Golang provides package-level encapsulation. There are no public, private, or protected keywords in Go. The only mechanism for controlling visibility is the use of uppercase and lowercase letters. 91 | 92 | Identifiers with a capital letter are exported. A capital letter means it is an exported identifier. 93 | Identifiers with lowercase letters are not exported. Lowercase letters indicate that the identifier is not exported and will only be accessible from the same package. 94 | There are five types of IDs that can be exported. 95 | 96 | - Structure 97 | - Structure method 98 | - Structure field 99 | - Function 100 | - Variable 101 | 102 | More details: 103 | [Encapsulation in Go (Golang)](https://golangbyexample.com/encapsulation-in-go/) 104 | 105 | ## Resources 106 | 107 | - [Объектно-ориентированное программирование в Golang](https://medium.com/nuances-of-programming/%D0%BE%D0%B1%D1%8A%D0%B5%D0%BA%D1%82%D0%BD%D0%BE-%D0%BE%D1%80%D0%B8%D0%B5%D0%BD%D1%82%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%BD%D0%BE%D0%B5-%D0%BF%D1%80%D0%BE%D0%B3%D1%80%D0%B0%D0%BC%D0%BC%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5-%D0%B2-golang-52f36f2fa837) 108 | 109 | ## README.md 110 | 111 | - eng [English](https://github.com/lumorow/golang-interview-preparation/blob/main/OOP/README.md) 112 | - ru [Русский](https://github.com/lumorow/golang-interview-preparation/blob/main/OOP/readme/README.ru.md) -------------------------------------------------------------------------------- /OOP/oop.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | type Grower interface { 6 | growUp() 7 | } 8 | 9 | type person struct { 10 | age int 11 | height int 12 | weight int 13 | male string 14 | name string 15 | } 16 | 17 | func NewPerson(age, height, weight int, male, name string) *person { 18 | return &person{ 19 | age: age, 20 | height: height, 21 | weight: weight, 22 | male: male, 23 | name: name, 24 | } 25 | } 26 | 27 | func (p *person) myNameIs() { 28 | fmt.Printf("My name is %s\n", p.name) 29 | } 30 | 31 | func (p *person) growUp() { 32 | p.height++ 33 | } 34 | 35 | func (p *person) gainWeight() { 36 | p.weight++ 37 | } 38 | 39 | type workman struct { 40 | person // Inheritance (inlining) 41 | placeOfWork string 42 | } 43 | 44 | type dog struct { 45 | } 46 | 47 | func (d *dog) growUp() { 48 | fmt.Printf("Gav! Gav!") // just example 49 | } 50 | 51 | func NewWorkman(placeOfWork string, p *person) *workman { 52 | return &workman{ 53 | placeOfWork: placeOfWork, 54 | person: *p, 55 | } 56 | } 57 | 58 | func main() { 59 | p := NewPerson(30, 183, 76, "male", "Michael") 60 | w := NewWorkman("Factory", p) 61 | w.myNameIs() 62 | d := &dog{} 63 | 64 | growers := []Grower{p, d} 65 | for _, gr := range growers { 66 | gr.growUp() // polymorphism 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /OOP/readme/README.ru.md: -------------------------------------------------------------------------------- 1 | # Объектно-ориентированное программирование в golang 2 | 3 |

4 | 5 | ## Разница между new и make 6 | `make` выделяет память для ссылочных типов данных (`slice`, `map`, `chan`), а также инициализирует 7 | их базовые структуры данных. 8 | 9 | `new` возвращает только указатели на инициализированную память и устанавливает для нее нулевое значение для типа `T`, 10 | то есть `0` для `int`, `''` для `string` и `nil` для ссылочных типов (`slice`, `map`, `chan`) 11 | 12 | ## Класс. Создание объекта класса 13 | 14 | В golang так таков классов нет, но используются структуры. У структур также имеются поля и методы, можно написать 15 | свой конструктор, но он будет представляться как обычный метод. 16 | 17 | ```golang 18 | type person struct { 19 | age int 20 | height int 21 | weight int 22 | male string 23 | name string 24 | } 25 | 26 | func NewPerson(age, height, weight int, male, name string) *person { 27 | return &person{ 28 | age: age, 29 | height: height, 30 | weight: weight, 31 | male: male, 32 | name: name, 33 | } 34 | } 35 | ``` 36 | 37 | ## Видимость структуры и полей 38 | В `Go` используется правило регистра первой буквы имени — если название начинается заглавной буквы — 39 | это `public`-доступ, если со строчной — `private`. 40 | Из примера выше можем увидеть, что структура `person` у нас не экспортируемая (приватная), 41 | поэтому она доступна только в данном пакете, где мы ее инициализировали. Но мы создали конструктор, 42 | который может нам создать этот объект по заданной инструкции внутри него. 43 | 44 | ## Реализация концепций в golang: 45 | ### Наследование 46 | 47 | В golang нет наследования, а используется `встраивание`. 48 | Самый простой случай использования наследования — дочерний тип должен иметь доступ к полям и методам родительского типа. 49 | Это делается в Go посредством `встраивания`. Базовая структура встраивается в дочернюю, после чего базовые поля 50 | и методы могут быть напрямую доступы дочерней структуре. 51 | 52 | Подробнее: 53 | [ООП: Наследование в Golang](https://github.com/MaksimDzhangirov/oop-go/blob/master/docs/inheritance.md) 54 | 55 | ### Полиморфизм 56 | #### Полиморфизм во время компиляции (Compile Time Polymorphism) - невозможен в golang 57 | 58 | При полиморфизме во время компиляции какую функцию вызывать решает компилятор. 59 | Примерами полиморфизма во время компиляции могут быть: 60 | - перегрузка метода/функции: существует более одного метода/функции с одним и тем же именем, 61 | но с разными сигнатурами или, возможно, с разными типами возвращаемых значений; 62 | - перегрузка операторов: один и тот же оператор используется для работы с разными типами данных. 63 | 64 | Go не поддерживает перегрузку метода. 65 | Go также не поддерживает перегрузку оператора. 66 | *** 67 | #### Полиморфизм во время выполнения (Run Time Polymorphism) - достигается за счет интерфейсов 68 | 69 | Полиморфизм во время выполнения означает, что решение о том какую функцию вызывать принимается во время выполнения. 70 | В [oop.go](https://github.com/lumorow/golang-interview-preparation/blob/main/OOP/oop.go) `interface Grower` создает контракт с 71 | `person` и `dog` структурами, которые имеют разную реализацию функции `growUp()`. 72 | 73 | Подробнее: 74 | [ООП: Полиморфизм в Golang](https://github.com/MaksimDzhangirov/oop-go/blob/master/docs/polymorphism.md) 75 | 76 | ### Абстрактные классы 77 | 78 | Интерфейс в Go не содержит полей, а также не позволяет определять методы внутри него. Любой тип должен реализовывать все методы интерфейса, чтобы иметь тип этого интерфейса. Существуют ситуации, когда полезно иметь реализацию метода по умолчанию, а также поля по умолчанию в Go. Прежде чем понять как это можно сделать давайте сначала разберёмся с требованиями для абстрактного класса: 79 | 80 | Абстрактный класс должен иметь поля по умолчанию 81 | Абстрактный класс должен иметь метод по умолчанию 82 | Не должно быть возможности непосредственно создать экземпляр абстрактного класса 83 | 84 | Подробнее: 85 | [ООП: Абстрактный класс в Golang](https://github.com/MaksimDzhangirov/oop-go/blob/master/docs/abstract_class.md) 86 | 87 | ### Инкапсуляция 88 | 89 | Golang обеспечивает инкапсуляцию на уровне пакета. В Go нет ключевых слов public, private или protected. Единственный механизм управления видимостью — использование прописных и строчных букв. 90 | 91 | Идентификаторы с прописной буквы экспортируются. Прописная буква означает, что это экспортируемый идентификатор. 92 | Идентификаторы со строчной буквы не экспортируются. Строчные буквы указывают на то, что идентификатор не экспортируется и будет доступен только из того же пакета. 93 | Существует пять видов идентификаторов, которые можно экспортировать. 94 | 95 | - Структура 96 | - Метод структуры 97 | - Поле структуры 98 | - Функция 99 | - Переменная 100 | 101 | Подробнее: 102 | [ООП: Инкапсуляция в Golang](https://github.com/MaksimDzhangirov/oop-go/blob/master/docs/encapsulation.md) 103 | 104 | ## Дополнительный материал 105 | 106 | - [Объектно-ориентированное программирование в Golang](https://medium.com/nuances-of-programming/%D0%BE%D0%B1%D1%8A%D0%B5%D0%BA%D1%82%D0%BD%D0%BE-%D0%BE%D1%80%D0%B8%D0%B5%D0%BD%D1%82%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%BD%D0%BE%D0%B5-%D0%BF%D1%80%D0%BE%D0%B3%D1%80%D0%B0%D0%BC%D0%BC%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5-%D0%B2-golang-52f36f2fa837) 107 | 108 | ## README.md 109 | 110 | - eng [English](https://github.com/lumorow/golang-interview-preparation/blob/main/OOP/README.md) 111 | - ru [Русский](https://github.com/lumorow/golang-interview-preparation/blob/main/OOP/readme/README.ru.md) -------------------------------------------------------------------------------- /Patterns/README.md: -------------------------------------------------------------------------------- 1 | # Design Patterns 2 | 3 |

4 | 5 | You can go straight to the explanation and implementation of patterns: 6 | [Design patterns with examples in Golang](https://github.com/AlexanderGrom/go-patterns) 7 | 8 | 9 | ## Generators. 10 | *** 11 | Such templates are needed to optimize the creation of a particular object. 12 | Generative patterns help create objects so that they communicate effectively with others and control their operation. 13 | 14 | ### Here are some examples: 15 | “Factory” - a separate class is invented to create new objects. It creates objects as copies of some standard; 16 | “Prototype” - the object itself creates copies of itself; 17 | Builder - similar to a factory, but new objects can be modified. They are created according to complex logic, and do not copy the reference one; 18 | “Singleton” - implies the presence of one large object that has global access to everything; 19 | “Lazy Initialization” is a method in which an object is not initialized immediately, but as it progresses. 20 | 21 | There are other patterns of varying complexity. For each task, one or another pattern is more optimal. The exact solution depends on the application, but the result should be an efficient and optimized system. 22 | 23 | ## Structural. 24 | *** 25 | If generative patterns are responsible for the creation and interaction of objects, then structural patterns are responsible for how these objects are structured in code. 26 | They describe how simple classes and objects are “assembled” into more complex ones. 27 | 28 | ### Here are examples: 29 | 30 | “Decorator” is a template for attaching additional behavior to an object; 31 | “Composite” is a pattern that combines several objects into a tree structure; 32 | “Bridge” is the principle of dividing an entity into abstraction and implementation, so that the theoretical structure and the concrete object can change independently; 33 | “Facade” is a method for reducing external calls to a single object; 34 | “Proxy” is a pattern similar to “Facade”, but with a special proxy object that controls access to the main one. 35 | 36 | These are just some examples. There are many more real patterns. 37 | 38 | ## Behavioral. 39 | *** 40 | These are design patterns that describe how objects behave and interact with others. 41 | They are used, for example, to divide responsibilities between different entities or to react 42 | for changes without errors. 43 | 44 | ### Examples of behavioral patterns: 45 | 46 | “Iterator” - one object sequentially gives access to various others, without using their complex descriptions; 47 | "Observer" - a pattern in which objects become aware of changes in others; 48 | “Keeper” (Memento) - helps to preserve an object in some state with the ability to return to it in the future; 49 | “Chain of Responsibility” - distributes responsibility for certain tasks to different objects; 50 | “Mediator” - organizes weak connections between objects to reduce their dependence on each other. 51 | How to understand which pattern to apply 52 | Each pattern has its own area of use. Experienced developers understand where to use what, based on the very specifics of the task, 53 | but at the beginning of the journey it can be difficult. 54 | 55 | ### Selecting a pattern into smaller steps: 56 | 57 | - highlight the entities that are used in the process; 58 | - think through the connections between them; 59 | - abstract the resulting system from a specific task; 60 | - see if the problem matches the meaning of something for which there is a pattern; 61 | - select several patterns from the desired group and see which one suits best; 62 | - think over a specific implementation of this pattern, taking into account the specifics of the task. 63 | 64 | It looks difficult, but over time the habit will come. Experienced developers have already gotten the hang of it, 65 | so they have much less problems with choosing a pattern. Once understanding is formed and practice is gained, 66 | it will be easier. 67 | 68 | ### Benefits of Design Patterns 69 | - Speed up and make writing code easier. 70 | - They allow you not to “reinvent the wheel”, but to use a ready-made, proven principle. 71 | - When used correctly, they make the code more readable and efficient. 72 | - Simplify mutual understanding between developers. 73 | - Helps get rid of common mistakes. 74 | - Do not depend on the programming language and its features. 75 | - Allows you to complete complex tasks faster and easier. 76 | 77 | ### Disadvantages of Design Patterns 78 | - Using patterns for the sake of patterns, on the contrary, complicates the code and confuses developers. 79 | - Incorrect use of one or another template can make the program less effective. 80 | - Patterns are not universal: a specific pattern will work for one task, but not another. 81 | - In the early stages of learning, it can be difficult to choose the appropriate pattern for a specific problem. 82 | - Due to its strong association with object-oriented programming, the use of patterns in other paradigms is limited. Although, for example, in functional programming they can be used - they are simply implemented differently. 83 | 84 | ### Is it worth using patterns? 85 | The presence of shortcomings does not make the idea of patterns bad. It's just a tool that needs to be used wisely. 86 | You should not use templates where you can do without them, just for the sake of “beauty”. If you use them in places 87 | where they are really needed - they will become good 88 | 89 | ## Resources 90 | *** 91 | - [Go Design patterns (Introduction)](https://medium.com/@mr_apr/go-design-patterns-introduction-9c5e57a3cb13) 92 | - [Паттерны проектирования с примерами на Golang](https://github.com/AlexanderGrom/go-patterns) 93 | - [Golang | Паттерны проектирования - Агентство цифровых технологий](https://www.youtube.com/playlist?list=PLxj7Nz8YYkVW5KHnsb9qWUDP2eD1TXl1N) 94 | 95 | ## README.md 96 | *** 97 | - eng [English](https://github.com/lumorow/golang-interview-preparation/blob/main/Patterns/README.md) 98 | - ru [Русский](https://github.com/lumorow/golang-interview-preparation/blob/main/Patterns/readme/README.ru.md) -------------------------------------------------------------------------------- /Patterns/readme/README.ru.md: -------------------------------------------------------------------------------- 1 | # Паттерны проектирования 2 | 3 |

4 | 5 | Можно перейти сразу на объяснение и реализацию паттернов: 6 | [Паттерны проектирования с примерами на Golang](https://github.com/AlexanderGrom/go-patterns) 7 | 8 | 9 | ## Порождающие. 10 | *** 11 | Такие шаблоны нужны, чтобы оптимизировать создание того или иного объекта. 12 | Порождающие паттерны помогают создавать объекты так, чтобы они эффективно общались с другими, и управлять их работой. 13 | 14 | ### Вот несколько примеров: 15 | «Фабрика» (Factory) — для создания новых объектов придумывают отдельный класс. Он создает объекты как копии некоего эталона; 16 | «Прототип» (Prototype) — объект сам создает свои копии; 17 | «Строитель» (Builder) — похож на фабрику, но новые объекты можно модифицировать. Они создаются по сложной логике, а не копируют эталонный; 18 | «Одиночка» (Singleton) — подразумевает наличие одного большого объекта, который имеет глобальный доступ ко всему; 19 | «Ленивая инициализация» (Lazy Initialization) — метод, при котором объект инициализируется не сразу, а по мере 20 | 21 | Существуют и другие шаблоны разной сложности. Для каждой задачи оптимальнее тот или иной паттерн. Конкретное решение зависит от задачи, но в результате должна получиться эффективная и оптимизированная система. 22 | 23 | ## Структурные. 24 | *** 25 | Если порождающие паттерны отвечают за создание и взаимодействие объектов, то структурные — за то, как эти объекты структурированы в коде. 26 | Они описывают, каким образом простые классы и объекты «собираются» в более сложные. 27 | 28 | ### Вот примеры: 29 | 30 | «Декоратор» (Decorator) — шаблон для подключения дополнительного поведения к объекту; 31 | «Компоновщик» (Composite) — паттерн, который объединяет несколько объектов в древовидную структуру; 32 | «Мост» (Bridge) — принцип разделения сущности на абстракцию и реализацию, чтобы теоретическая структура и конкретный объект могли изменяться независимо; 33 | «Фасад» (Facade) — метод для сведения внешних вызовов к одному объекту; 34 | «Заместитель» (Proxy) — паттерн, похожий на «Фасад», но со специальным объектом-заместителем, который контролирует доступ к основному. 35 | Это только некоторые примеры. Реальных паттернов намного больше. 36 | 37 | ## Поведенческие. 38 | *** 39 | Это паттерны проектирования, которые описывают, как объекты себя ведут и взаимодействуют с другими. 40 | Их используют, например, для разделения обязанностей между разными сущностями или для реагирования 41 | на изменения без ошибок. 42 | 43 | ### Примеры поведенческих паттернов: 44 | 45 | «Итератор» (Iterator) — один объект последовательно дает доступ к разным другим, при этом не использует их сложные описания; 46 | «Наблюдатель» (Observer) – шаблон, при котором объекты узнают об изменениях в других; 47 | «Хранитель» (Memento) — помогает сохранить объект в каком-то состоянии с возможностью вернуться к нему в будущем; 48 | «Цепочка ответственности» (Chain of Responsibility) — распределяет ответственность за те или иные задачи на разные объекты; 49 | «Посредник» (Mediator) — организует слабые связи между объектами, чтобы снизить их зависимость друг от друга. 50 | Как понять, какой паттерн применить 51 | У каждого паттерна своя область использования. Опытные разработчики понимают, где что использовать, по самой специфике задачи, 52 | но в начале пути это может быть сложно. 53 | 54 | ### Выбор паттерна на более мелкие шаги: 55 | 56 | - выделить сущности, которые используются в процессе; 57 | - продумать связи между ними; 58 | - абстрагировать получившуюся систему от конкретной задачи; 59 | - посмотреть, не подходит ли проблема по смыслу на что-то, для чего есть паттерн; 60 | - выбрать несколько паттернов из нужной группы и посмотреть какой подходит лучше; 61 | - продумать конкретную реализацию этого паттерна с учетом особенностей задачи. 62 | 63 | - Это выглядит сложно, но со временем придет привычка. Опытные разработчики уже «набили руку», поэтому проблемы с выбором паттерна у них возникают намного реже. Когда сформируется понимание и наберется практика, будет проще. 64 | 65 | ### Преимущества паттернов проектирования 66 | - Ускоряют и облегчают написание кода. 67 | - Позволяют не «изобретать велосипед», а воспользоваться готовым проверенным принципом. 68 | - При грамотном использовании делают код более читаемым и эффективным. 69 | - Упрощают взаимопонимание между разработчиками. 70 | - Помогают избавиться от типовых ошибок. 71 | - Не зависят от языка программирования и его особенностей. 72 | - Позволяют реализовывать сложные задачи быстрее и проще. 73 | 74 | ### Недостатки паттернов проектирования 75 | - Использование паттернов ради паттернов, наоборот, усложняет код и запутывает разработчиков. 76 | - Неправильное применение того или иного шаблона способно сделать программу менее эффективной. 77 | - Паттерны не универсальны: в одной задаче конкретный паттерн подойдет, в другой нет. 78 | - На ранних этапах изучения бывает сложно выбрать подходящий для конкретной проблемы паттерн. 79 | - Из-за сильной связи с объектно-ориентированным программированием использование паттернов в других парадигмах ограничено. Хотя, например, в функциональном программировании они могут применяться — просто реализуются иначе. 80 | 81 | ### Стоит ли пользоваться паттернами 82 | Наличие недостатков не делает саму идею паттернов плохой. Просто это инструмент, которым нужно пользоваться с умом. 83 | Не стоит применять шаблоны там, где можно без них обойтись, просто ради «красоты». Если же использовать их в местах, 84 | где они действительно нужны – они станут хорошей помощью в работе программиста. 85 | 86 | ## Дополнительный материал 87 | *** 88 | - [Go Design patterns (Introduction)](https://medium.com/@mr_apr/go-design-patterns-introduction-9c5e57a3cb13) 89 | - [Паттерны проектирования с примерами на Golang](https://github.com/AlexanderGrom/go-patterns) 90 | - [Golang | Паттерны проектирования - Агентство цифровых технологий](https://www.youtube.com/playlist?list=PLxj7Nz8YYkVW5KHnsb9qWUDP2eD1TXl1N) 91 | 92 | ## README.md 93 | *** 94 | - eng [English](https://github.com/lumorow/golang-interview-preparation/blob/main/Patterns/README.md) 95 | - ru [Русский](https://github.com/lumorow/golang-interview-preparation/blob/main/Patterns/readme/README.ru.md) -------------------------------------------------------------------------------- /PostgreSQL/README.md: -------------------------------------------------------------------------------- 1 | # PostgreSQL 2 | 3 | In PostgreSQL, a transaction is defined by a set of SQL commands surrounded by `BEGIN` and `COMMIT` commands. 4 | So our bank transaction would look like this: 5 | 6 | ```sql 7 | BEGIN; 8 | UPDATE accounts SET balance = balance - 100.00 9 | WHERE name = 'Alice'; 10 | -- ... 11 | COMMIT; 12 | ``` 13 | If during the execution of a transaction we decide that we do not want to commit its changes (for example, because it turned out that 14 | that Alice's balance has become negative), we can issue the command `ROLLBACK` instead of `COMMIT`, and all our changes will be 15 | cancelled. 16 | 17 | PostgreSQL actually processes each SQL statement as a transaction. If you do not insert the `BEGIN` command, 18 | then each individual statement will be implicitly surrounded by `BEGIN` and `COMMIT` commands (if successful). 19 | A group of statements surrounded by `BEGIN` and `COMMIT` commands is sometimes called a transaction block. 20 | 21 | ## ACID or 4 transaction properties 22 | 23 | Before we begin to consider transaction isolation levels, let us briefly recall the basic requirements for a transactional system. 24 | 25 | - `Atomicity` - is expressed in the fact that the transaction must be completed as a whole or not performed at all. 26 | 27 | - `Consistency` - ensures that as transactions are performed, data moves from one consistent state 28 | to another, that is, the transaction cannot destroy the mutual consistency of the data. 29 | 30 | - `Isolation` - localization of user processes means that transactions competing for access to the database are physically processed sequentially, 31 | isolated from each other, but to users it appears as if they are running in parallel. 32 | 33 | - `Durability`- error resistance - if a transaction is completed successfully, then the changes in the data that were made by it cannot be lost under any circumstances. 34 | 35 | ## Transactions and isolation levels 36 | 37 | The standard describes the following special conditions that are not permitted for the various insulation levels: 38 | 39 | - `Dirty reading`. A transaction reads data written by a concurrent pending transaction. 40 | 41 | - `Unrepeatable reading`. The transaction re-reads the same data as before and discovers that it was modified by another transaction (which completed after the first read). 42 | 43 | - `Phantom reading`. A transaction re-executes a query that returns a set of rows for some condition and discovers that the set of rows that satisfy the condition has changed due to a transaction that completed during that time. 44 | 45 | - `Serialization anomaly`. The result of successfully committing a group of transactions turns out to be inconsistent under all possible options for executing these transactions in turn. 46 | 47 | | Isolation level | Dirty r eading | Unique reading | Phantom reading | Serialization anomaly | 48 | |-------------------|------------------------|----------------|------------------------|-----------------------| 49 | | `Read uncommited` | Allowed, but not in PG | Perhaps | Perhaps | Perhaps | 50 | | `Read committed` | Impossible | Perhaps | Perhaps | Perhaps | 51 | | `Repeatable read` | Impossible | Impossible | Allowed, but not in PG | Perhaps | 52 | | `Serializable` | Impossible | Impossible | Impossible | Impossible | 53 | 54 | ## Indexes in PostgreSQL 55 | 56 | To improve search performance, auxiliary structures - indexes - are created. Using indexes, 57 | we can significantly increase the search speed, because the data in the index is stored in a form that allows us to 58 | search does not consider areas that obviously cannot contain the searched elements. 59 | 60 | PostgreSQL supports different types of indexes for different tasks: 61 | 62 | - `B-tree` covers the widest class of problems, since it is applicable to any data that can be sorted. 63 | - `GiST` and `SP-GiST` can be useful when working with geometric objects and for creating completely new types of indexes 64 | for new data types. 65 | - Beyond the scope of this article was another important type of index - `GIN`. `GIN` indexes are useful for organizing full-text 66 | search and for indexing data types such as arrays or `jsonb`. 67 | 68 | 69 | ## Resources 70 | 71 | - [Transaction isolation in PostgreSQL (DEV Meetup November 2019)](https://www.youtube.com/watch?v=h4-o0kQz5lo&t=11s&ab_channel=QAHub) 72 | - [Transaction isolation (PostgresPro)](https://postgrespro.ru/docs/postgrespro/9.5/transaction-iso) 73 | - [Transaction isolation levels with examples in PostgreSQL (habr)](https://habr.com/ru/articles/317884/) 74 | - [Indexes in PostgreSQL - 1 (habr)](https://habr.com/ru/companies/postgrespro/articles/326096/) 75 | - [Indexes in PostgreSQL](https://tproger.ru/articles/indeksy-v-postgresql) 76 | - [Indexes in PostgreSQL - 3 (habr)](https://habr.com/ru/companies/postgrespro/articles/328280/) 77 | 78 | ## README.md 79 | 80 | - eng [English](https://github.com/lumorow/golang-interview-preparation/blob/main/PosgreSQL/README.md) 81 | - ru [Русский](https://github.com/lumorow/golang-interview-preparation/blob/main/PosgreSQL/readme/README.ru.md) 82 | -------------------------------------------------------------------------------- /PostgreSQL/readme/REDANME.ru.md: -------------------------------------------------------------------------------- 1 | # PostgreSQL 2 | 3 | В Postgres Pro транзакция определяется набором SQL-команд, окружённым командами `BEGIN` и `COMMIT`. 4 | Таким образом, наша банковская транзакция должна была бы выглядеть так: 5 | 6 | ```sql 7 | BEGIN; 8 | UPDATE accounts SET balance = balance - 100.00 9 | WHERE name = 'Alice'; 10 | -- ... 11 | COMMIT; 12 | ``` 13 | Если в процессе выполнения транзакции мы решим, что не хотим фиксировать её изменения (например, потому что оказалось, 14 | что баланс Алисы стал отрицательным), мы можем выполнить команду `ROLLBACK` вместо `COMMIT`, и все наши изменения будут 15 | отменены. 16 | 17 | Postgres Pro на самом деле отрабатывает каждый SQL-оператор как транзакцию. Если вы не вставите команду `BEGIN`, 18 | то каждый отдельный оператор будет неявно окружён командами `BEGIN` и `COMMIT` (в случае успешного завершения). 19 | Группу операторов, окружённых командами `BEGIN` и `COMMIT` иногда называют блоком транзакции. 20 | 21 | ## ACID или 4 свойства транзакций 22 | 23 | Прежде чем приступим к рассмотрению уровней изоляции транзакции в паре слов вспомним об основных требованиях к транзакционной системе. 24 | 25 | - `Atomicity` (атомарность) — выражается в том, что транзакция должна быть выполнена в целом или не выполнена вовсе. 26 | 27 | - `Consistency` (согласованность) — гарантирует, что по мере выполнения транзакций, данные переходят из одного согласованного состояния 28 | в другое, то есть транзакция не может разрушить взаимной согласованности данных. 29 | 30 | - `Isolation` (изолированность) — локализация пользовательских процессов означает, что конкурирующие за доступ к БД транзакции физически обрабатываются последовательно, 31 | изолированно друг от друга, но для пользователей это выглядит, как будто они выполняются параллельно. 32 | 33 | - `Durability` (долговечность) — устойчивость к ошибкам — если транзакция завершена успешно, то те изменения в данных, которые были ею произведены, не могут быть потеряны ни при каких обстоятельствах. 34 | 35 | ## Транзакции и уровни изоляций 36 | 37 | Стандарт описывает следующие особые условия, недопустимые для различных уровней изоляции: 38 | 39 | - `«Грязное» чтение`. Транзакция читает данные, записанные параллельной незавершённой транзакцией. 40 | 41 | - `Неповторяемое чтение`. Транзакция повторно читает те же данные, что и раньше, и обнаруживает, что они были изменены другой транзакцией (которая завершилась после первого чтения). 42 | 43 | - `Фантомное чтение`. Транзакция повторно выполняет запрос, возвращающий набор строк для некоторого условия, и обнаруживает, что набор строк, удовлетворяющих условию, изменился из-за транзакции, завершившейся за это время. 44 | 45 | - `Аномалия сериализации`. Результат успешной фиксации группы транзакций оказывается несогласованным при всевозможных вариантах исполнения этих транзакций по очереди. 46 | 47 | 48 | 49 | | Уровень изоляции | «Грязное» чтение | Неповторяемое чтение | Фантомное чтение | Аномалия сериализации | 50 | |-----------------------------------------------------|-------------------------|-----------------------|-------------------------|------------------------| 51 | | `Read uncommited` (Чтение незафиксированных данных) | Допускается, но не в PG | Возможно | Возможно | Возможно | 52 | | `Read committed` (Чтение зафиксированных данных) | Невозможно | Возможно | Возможно | Возможно | 53 | | `Repeatable read` (Повторяемое чтение) | Невозможно | Невозможно | Допускается, но не в PG | Возможно | 54 | | `Serializable` (Сериализуемость) | Невозможно | Невозможно | Невозможно | Невозможно | 55 | 56 | ## Индексы в PostgreSQL 57 | 58 | Для повышения производительности поиска создаются вспомогательные структуры — индексы. Используя индексы, 59 | можно существенно поднять скорость поиска, потому что данные в индексе хранятся в форме, позволяющей нам в процессе 60 | поиска не рассматривать области, которые заведомо не могут содержать искомые элементы. 61 | 62 | PostgreSQL поддерживает разные типы индексов для разных задач: 63 | 64 | - `B-дерево` покрывает широчайший класс задач, т. к. применимо к любым данным, которые можно отсортировать. 65 | - `GiST` и `SP-GiST` могут быть полезны при работе с геометрическими объектами и для создания совершенно новых типов индексов 66 | для новых типов данных. 67 | - За рамками этой статьи оказался ещё один важный тип индексов — `GIN`. `GIN` индексы полезны для организации полнотекстового 68 | поиска и для индексации таких типов данных, как массивы или `jsonb`. 69 | 70 | 71 | ## Дополнительный материал 72 | - [Изоляция транзакций в PostgreSQL (DEV Meetup November 2019)](https://www.youtube.com/watch?v=h4-o0kQz5lo&t=11s&ab_channel=QAHub) 73 | - [Изоляция транзакций (PostgresPro)](https://postgrespro.ru/docs/postgrespro/9.5/transaction-iso) 74 | - [Уровни изоляции транзакций с примерами на PostgreSQL (habr)](https://habr.com/ru/articles/317884/) 75 | - [Индексы в PostgreSQL — 1 (habr)](https://habr.com/ru/companies/postgrespro/articles/326096/) 76 | - [Индексы в PostgreSQL](https://tproger.ru/articles/indeksy-v-postgresql) 77 | - [Индексы в PostgreSQL — 3 (habr)](https://habr.com/ru/companies/postgrespro/articles/328280/) 78 | 79 | ## README.md 80 | 81 | - eng [English](https://github.com/lumorow/golang-interview-preparation/blob/main/PosgreSQL/README.md) 82 | - ru [Русский](https://github.com/lumorow/golang-interview-preparation/blob/main/PosgreSQL/readme/README.ru.md) 83 | -------------------------------------------------------------------------------- /Practical/README.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lumorow/golang-interview-preparation/776f95d5080a09bec52af0b5d0defc3a55529add/Practical/README.md -------------------------------------------------------------------------------- /Practical/readme/README.ru.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lumorow/golang-interview-preparation/776f95d5080a09bec52af0b5d0defc3a55529add/Practical/readme/README.ru.md -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Golang interview preparation 2 | 3 | This page is dedicated to strengthening and possibly 4 | introducing new knowledge for you in the golang programming language. 5 | This covers both theoretical and practical parts. 6 | The page will be gradually supplemented and edited. 7 | 8 |

9 | 10 | ## Topics 11 | 12 | - [Basic knowledge of the language](https://github.com/lumorow/golang-interview-preparation/tree/main/Basic): let's talk about data types and working with them. 13 | - [Introduction to Object-Oriented Programming in Go (GO OOP)](https://github.com/lumorow/golang-interview-preparation/tree/main/OOP): How object oriented programming is implemented in golang. 14 | - [Multithreading](https://github.com/lumorow/golang-interview-preparation/tree/main/Multithreading): how threads work in golang. 15 | - [Design Patterns](https://github.com/lumorow/golang-interview-preparation/tree/main/Patterns): Design patterns and their implementation in golang. 16 | - [Network](https://github.com/lumorow/golang-interview-preparation/tree/main/Networking): basic knowledge of networks. 17 | - [Docker](https://github.com/lumorow/golang-interview-preparation/tree/main/Docker): highlights from docker. 18 | - [Kafka](https://github.com/lumorow/golang-interview-preparation/tree/main/Kafka): highlights with Kafka. 19 | - [PostgreSQL](https://github.com/lumorow/golang-interview-preparation/tree/main/PostgreSQL): highlights of PostgreSQL. 20 | - [Golang under the hood](https://github.com/lumorow/golang-interview-preparation/tree/main/UnderHood): what happens while our program is running. 21 | - [Language Features with Examples](https://github.com/lumorow/golang-interview-preparation/tree/main/Practical): Interesting points in golang that you need to understand. 22 | 23 | 24 | ## Your first program 25 | 26 | How to Write Go Code https://go.dev/doc/code#Workspaces 27 | 28 | ## Helpful Learning Resources 29 | 30 | #### RUS: 31 | - [Avito.code](https://www.youtube.com/playlist?list=PLknJ4Vr6efQFHIBKN_igl7Zl6nMbcjrsd) 32 | - [Уроки по GoLang. Николай Тузов — Golang](https://www.youtube.com/playlist?list=PLFAQFisfyqlXt2kAMc1L2NC9NgHPSQgvQ) 33 | - [REST API](https://www.youtube.com/playlist?list=PLbTTxxr-hMmyFAvyn7DeOgNRN8BQdjFm8) 34 | - [Всё про конкурентность в Go](https://www.youtube.com/watch?v=mvUiw9ilqn8) 35 | - [Антон Сергеев, «Go под капотом»](https://www.youtube.com/watch?v=rloqQY9CT8I&t=7s) 36 | - [Как устроен garbage collector в Go 1.9 - Андрей Дроздов, Avito](https://www.youtube.com/watch?v=CX4GSErFenI) 37 | - Книга: Цукалос Михалис Golang для профи: работа с сетью, многопоточность, структуры данных и машинное обучение с Go 38 | - Книга: Мэтью Титмус: Облачный GO 39 | 40 | #### ENG: 41 | - [All Design Patterns in Go (Golang)](https://golangbyexample.com/all-design-patterns-golang/) 42 | - [Questions on Golang Basics](https://www.educative.io/blog/50-golang-interview-questions) 43 | - [50 Top Golang Interview Questions and Answers for 2023](https://hackr.io/blog/golang-interview-questions-and-answers) 44 | - Book: Juan M. Tirado: Build Systems With Go: Everything a Gopher must know 45 | - Book: Teiva Harsanyi: 100 Go Mistakes and How to Avoid Them 46 | 47 | ## README.md 48 | 49 | - eng [English](https://github.com/lumorow/golang-interview-preparation/blob/main/README.md) 50 | - ru [Русский](https://github.com/lumorow/golang-interview-preparation/tree/main/readme/README.ru.md) 51 | -------------------------------------------------------------------------------- /UnderHood/README.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lumorow/golang-interview-preparation/776f95d5080a09bec52af0b5d0defc3a55529add/UnderHood/README.md -------------------------------------------------------------------------------- /img/basicgo.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lumorow/golang-interview-preparation/776f95d5080a09bec52af0b5d0defc3a55529add/img/basicgo.jpg -------------------------------------------------------------------------------- /img/concurrencyGo.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lumorow/golang-interview-preparation/776f95d5080a09bec52af0b5d0defc3a55529add/img/concurrencyGo.jpeg -------------------------------------------------------------------------------- /img/deadlock.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lumorow/golang-interview-preparation/776f95d5080a09bec52af0b5d0defc3a55529add/img/deadlock.png -------------------------------------------------------------------------------- /img/golang-any-interface-fs8.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lumorow/golang-interview-preparation/776f95d5080a09bec52af0b5d0defc3a55529add/img/golang-any-interface-fs8.webp -------------------------------------------------------------------------------- /img/gopher_russian.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lumorow/golang-interview-preparation/776f95d5080a09bec52af0b5d0defc3a55529add/img/gopher_russian.png -------------------------------------------------------------------------------- /img/gophermap.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lumorow/golang-interview-preparation/776f95d5080a09bec52af0b5d0defc3a55529add/img/gophermap.png -------------------------------------------------------------------------------- /img/gophslice.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /img/hmap.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lumorow/golang-interview-preparation/776f95d5080a09bec52af0b5d0defc3a55529add/img/hmap.png -------------------------------------------------------------------------------- /img/map.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /img/oopgo.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lumorow/golang-interview-preparation/776f95d5080a09bec52af0b5d0defc3a55529add/img/oopgo.jpeg -------------------------------------------------------------------------------- /img/patterns.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lumorow/golang-interview-preparation/776f95d5080a09bec52af0b5d0defc3a55529add/img/patterns.webp -------------------------------------------------------------------------------- /img/pre_gophers.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lumorow/golang-interview-preparation/776f95d5080a09bec52af0b5d0defc3a55529add/img/pre_gophers.png -------------------------------------------------------------------------------- /img/rest-api.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lumorow/golang-interview-preparation/776f95d5080a09bec52af0b5d0defc3a55529add/img/rest-api.png -------------------------------------------------------------------------------- /img/rwchan.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lumorow/golang-interview-preparation/776f95d5080a09bec52af0b5d0defc3a55529add/img/rwchan.jpeg -------------------------------------------------------------------------------- /img/strings.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lumorow/golang-interview-preparation/776f95d5080a09bec52af0b5d0defc3a55529add/img/strings.png -------------------------------------------------------------------------------- /readme/README.ru.md: -------------------------------------------------------------------------------- 1 | # Подготовка к собеседованию на Golang 2 | 3 | Эта страница посвящена закреплению и, возможно, появлению 4 | для вас новых знаний по языку программирования golang. 5 | Это касается как теоретической, так и практической части. 6 | Страница будет постепенно дополняться и редактироваться. 7 | 8 |

9 | 10 | ## Темы 11 | 12 | - [Основные знания по языку](https://github.com/lumorow/golang-interview-preparation/tree/main/Basic): поговорим о типах данных и работе с ними. 13 | - [Введение в объектно-ориентированное программирование на Go (ООП GO)](https://github.com/lumorow/golang-interview-preparation/tree/main/OOP): как объектно-ориентированное программирование реализовано в golang. 14 | - [Многопоточность](https://github.com/lumorow/golang-interview-preparation/tree/main/Multithreading): как работают потоки в golang. 15 | - [Патерны проектирования](https://github.com/lumorow/golang-interview-preparation/tree/main/Patterns): шаблоны проектирования и их реализация в golang. 16 | - [Сеть](https://github.com/lumorow/golang-interview-preparation/tree/main/Networking): базовые знания по сетям. 17 | - [Docker](https://github.com/lumorow/golang-interview-preparation/tree/main/Docker): основные моменты по docker. 18 | - [Kafka](https://github.com/lumorow/golang-interview-preparation/tree/main/Kafka): основные моменты по Kafka. 19 | - [PostgreSQL](https://github.com/lumorow/golang-interview-preparation/tree/main/PostgreSQL): основные моменты по PostgreSQL. 20 | - [Голанг под капотом](https://github.com/lumorow/golang-interview-preparation/tree/main/UnderHood): что происходит во время работы нашей программы. 21 | - [Особенности языка на примерах](https://github.com/lumorow/golang-interview-preparation/tree/main/Practical): интересные моменты в golang, которые вам нужно понять. 22 | 23 | ## Твоя первая программа 24 | 25 | Как написать код Go https://go.dev/doc/code#Workspaces 26 | 27 | ## Полезные учебные ресурсы 28 | 29 | #### RUS: 30 | - [Avito.code](https://www.youtube.com/playlist?list=PLknJ4Vr6efQFHIBKN_igl7Zl6nMbcjrsd) 31 | - [Уроки по GoLang. Николай Тузов — Golang](https://www.youtube.com/playlist?list=PLFAQFisfyqlXt2kAMc1L2NC9NgHPSQgvQ) 32 | - [REST API](https://www.youtube.com/playlist?list=PLbTTxxr-hMmyFAvyn7DeOgNRN8BQdjFm8) 33 | - [Всё про конкурентность в Go](https://www.youtube.com/watch?v=mvUiw9ilqn8) 34 | - [Антон Сергеев, «Go под капотом»](https://www.youtube.com/watch?v=rloqQY9CT8I&t=7s) 35 | - [Как устроен garbage collector в Go 1.9 - Андрей Дроздов, Avito](https://www.youtube.com/watch?v=CX4GSErFenI) 36 | - Книга: Цукалос Михалис Golang для профи: работа с сетью, многопоточность, структуры данных и машинное обучение с Go 37 | - Книга: Мэтью Титмус: Облачный GO 38 | - Книга: Juan M. Tirado: Build Systems With Go: Everything a Gopher must know 39 | 40 | #### ENG: 41 | - [All Design Patterns in Go (Golang)](https://golangbyexample.com/all-design-patterns-golang/) 42 | - [Questions on Golang Basics](https://www.educative.io/blog/50-golang-interview-questions) 43 | - [50 Top Golang Interview Questions and Answers for 2023](https://hackr.io/blog/golang-interview-questions-and-answers) 44 | - Book: Teiva Harsanyi: 100 Go Mistakes and How to Avoid Them 45 | 46 | ## README.md 47 | 48 | - eng [English](https://github.com/lumorow/golang-interview-preparation/blob/main/README.md) 49 | - ru [Русский](https://github.com/lumorow/golang-interview-preparation/tree/main/readme/README.ru.md) 50 | --------------------------------------------------------------------------------