каверзные вопросы, а не повтор фичtricky questions, not a rehash of features

Вопросы на собеседованииInterview questions

Не повтор материала из language/oop — а вопросы в формате, в котором их реально задают: заимствование и время жизни, конкурентность без гонок данных, устройство Vec/String/HashMap, задачи «почему это не компилируется». Каркас: 4 категории, страницы ещё не написаны.Not a rehash of language/oop — questions in the format they're actually asked: borrowing and lifetimes, data-race-free concurrency, Vec/String/HashMap internals, "why doesn't this compile" exercises. Skeleton: 4 categories, pages not yet written.

Язык, типы, памятьLanguage, types, memory

Почему не компилируется два Why doesn't two &mut одновременно? at once compile?borrow checker гарантирует либо одну изменяемую ссылку, либо любое число неизменяемых — на этапе компиляции, без рантайм-издержек.the borrow checker allows either one mutable reference or any number of shared ones — enforced at compile time, with zero runtime cost.interview Время жизни в сигнатуре функции — зачем?Lifetimes in a function signature — why?компилятор не выводит связь времён жизни между несколькими ссылочными параметрами и возвращаемым значением без явной аннотации.the compiler can't infer the lifetime relationship between multiple reference parameters and the return value without an explicit annotation.interview Copy vsvs Clone — в чём разница?— what's the difference?Copy — неявное побитовое копирование для простых типов, Clone — явный вызов, может быть дорогим (глубокое копирование). is an implicit bitwise copy for simple types, Clone is explicit and can be expensive (deep copy).interview unwrap() в продакшене — почему это red flag?in production — why is it a red flag?паникует при None/Err вместо явной обработки — приемлемо в прототипах и тестах, не в библиотечном/сервисном коде.panics on None/Err instead of handling it explicitly — fine in prototypes/tests, not in library or service code. dyn Trait vs generics — когда что?vs generics — when to use which?generics + monomorphization — быстрее, но раздувает бинарник; dyn Trait — один код на все типы, но vtable и косвенный вызов.generics + monomorphization are faster but bloat the binary; dyn Trait shares one code path across types at the cost of a vtable and indirect calls.interview unsafe — что именно оно разрешает?— what does it actually unlock?разыменование raw-указателей, вызов unsafe-функций/FFI, доступ к mutable static — не отключает заимствование целиком.dereferencing raw pointers, calling unsafe functions/FFI, accessing mutable statics — it does not turn off borrow checking entirely.

КонкурентностьConcurrency

Send и& Sync — в чём разница?— what's the difference?Send — тип можно передать между потоками; Sync — на тип можно ссылаться из нескольких потоков одновременно. means a type can be transferred between threads; Sync means a type can be referenced from multiple threads at once.interview Почему Rc неWhy isn't Rc Send?счётчик ссылок не атомарен — Arc делает то же самое с atomic-инкрементом ценой небольшого оверхеда.its refcount isn't atomic — Arc does the same job with an atomic increment at a small overhead cost.interview Mutex<T> — почему нельзя забыть разлочить?— why can't you forget to unlock it?MutexGuard реализует RAII — блокировка снимается автоматически в деструкторе при выходе из области видимости. implements RAII — the lock releases automatically in its destructor on scope exit. async fn — когда реально начинает выполняться?— when does it actually start running?Future ленив — код не выполняется, пока его не опросит (poll) исполнитель через .await или executor.a Future is lazy — nothing runs until an executor polls it via .await or the runtime.interview Deadlock возможен ли в safe Rust?— is it possible in safe Rust?да — borrow checker предотвращает data races, но не deadlock'и (два мьютекса, захваченные в разном порядке).yes — the borrow checker prevents data races, not deadlocks (two mutexes locked in different orders).

Устройство структур данныхData structure internals

языковая специфика, не общий CS — см. theory/02-algorithms-foundationslanguage-specific, not general CS — see theory/02-algorithms-foundations
Vec<T> — что хранится на стеке, а что на куче?what lives on the stack vs the heap?на стеке — указатель, длина, capacity (24 байта на 64-бит); сами элементы всегда в куче.the pointer, length, and capacity live on the stack (24 bytes on 64-bit); the elements themselves always live on the heap.interview String vsvs &strString — владеющий растущий буфер на куче; &str — невладеющий срез, может указывать в String, в статику или в Vec<u8>.String is an owning, growable heap buffer; &str is a borrowed slice that can point into a String, static data, or a Vec<u8>.interview HashMap — почему по умолчанию не самый быстрый хеш?why isn't the default hasher the fastest one?SipHash защищает от HashDoS-атак ценой скорости; для доверенных данных можно подключить более быстрый хешер (FxHash и другие).defends against HashDoS attacks at the cost of speed; for trusted data you can swap in a faster hasher (FxHash and others). Box<T> — зачем нужен, если есть владение по умолчанию?why do you need it if ownership already exists?выносит данные на кучу — нужен для рекурсивных типов (иначе бесконечный размер) и передачи trait-объектов.moves data onto the heap — needed for recursive types (otherwise infinite size) and for passing trait objects.interview Option<&T> — почему тот же размер, что иwhy is it the same size as &T?niche optimization — компилятор использует невозможное значение указателя (0) как представление None, без лишнего тега. — the compiler uses an impossible pointer value (0) to represent None, with no extra tag needed.

Поведенческие задачиBehavioral exercises

«почему это не компилируется?why doesn't this compile?»
Итератор мутирует коллекцию — почему ошибка?An iterator mutates the collection — why the error?итератор держит неизменяемое заимствование всей коллекции — одновременная мутация нарушает правило заимствования.the iterator holds a shared borrow of the whole collection — mutating at the same time violates the borrowing rule.interview Возврат ссылки на локальную переменнуюReturning a reference to a local variableкомпилятор ловит потенциальный dangling reference на этапе компиляции — то, что в C++ было бы UB в рантайме.the compiler catches the potential dangling reference at compile time — what would be runtime UB in C++.interview match без обработки всех вариантов enummissing a variant of an enumкомпилятор требует исчерпывающего match — новый вариант enum ломает сборку везде, где он не обработан, вместо тихого бага в рантайме.the compiler requires an exhaustive match — a new enum variant breaks the build everywhere it's unhandled, instead of a silent runtime bug.interview Перемещение значения из захваченной переменнойMoving a value out of a captured variableпосле move в замыкание переменная больше не используется во внешней области — компилятор отслеживает это по каждому пути кода.after a move into a closure, the variable can no longer be used outside — the compiler tracks this along every code path. Целочисленное переполнение в debug vsvs releaseв debug-сборке — паника, в release — тихий wraparound (если не включена явная проверка) — частый сюрприз.panics in debug builds, silently wraps in release (unless checks are explicitly enabled) — a common surprise.interview

статус и связь с остальными разделамиstatus & relation to the other sections

Это каркас: 4 категории и 21 вопрос зафиксированы, страницы ещё не написаны. В отличие от language/ (справочник по фичам) и oop/ (концепции ООП), здесь материал организован вокруг формата реального собеседования: короткий вопрос → ловушка → объяснение. Многие вопросы в Rust формулируются как «почему это не компилируется» — компилятор ловит на этапе сборки то, что в C++ было бы рантайм-багом или UB.This is a skeleton: 4 categories and 21 questions are locked in, pages not yet written. Unlike language/ (a feature reference) and oop/ (OOP concepts), material here is organized around the actual interview format: a short question → the trap → the explanation. Many Rust questions take the form "why doesn't this compile" — the compiler catches at build time what would be a runtime bug or UB in C++.