структуры, трейты, перечисления вместо классовstructs, traits, enums instead of classes

ООП в Rustin Rust

В Rust нет классов и деструкторов в классическом виде — их работу берут на себя struct/enum, ассоциированные функции и трейт Drop. Из 14 базовых концепций ООП сюда не попали 4, у которых в Rust нет реального языкового аналога даже по конвенции: перегрузка сигнатур, свойства, наследование, события. Взамен добавлен полиморфизм — statically через generics/монoморфизацию и dynamically через dyn Trait. Плюс то, что делает Rust особенным в этой области: трейты как интерфейсы, newtype, derive-макросы, orphan rule. Каркас: 15 карточек, страницы ещё не написаны.Rust has no classes or destructors in the classic sense — struct/enum, associated functions, and the Drop trait do that work instead. Of the 14 baseline OOP concepts, 4 are missing here because Rust has no real language analogue for them even by convention: signature overloading, properties, inheritance, events. Polymorphism was added in their place — static via generics/monomorphization and dynamic via dyn Trait. Plus what makes Rust distinctive in this space: traits as interfaces, the newtype pattern, derive macros, the orphan rule. Skeleton: 15 cards, pages not yet written.

Базовые концепции ООПBaseline OOP concepts

Определение классов, инициализацияClass definition & initializationstruct вместо class — только данные, без встроенного контроля доступа между полями; инициализация — единственное выражение с фигурными скобками, все поля обязаны быть заданы сразу. instead of class — data only, no built-in access control between fields; initialization is a single brace expression, every field must be set at once.interview КонструкторыConstructorsнет конструкторов как синтаксиса — no constructor syntax — Self::new() это чистая конвенция, а не гарантия языка; тип валиден только когда заполнены все поля. is pure convention, not a language guarantee; the type is valid only once every field is initialized.interview ДеструкторыDestructorsтрейт the Drop с единственным методом drop(&mut self) — вызывается компилятором автоматически при выходе из области видимости, ручной вызов запрещён (есть trait with a single drop(&mut self) method — called automatically by the compiler on scope exit; calling it manually is forbidden (use std::mem::drop вместо этого). instead).interview ПоляFieldsприватны по умолчанию на уровне модуля, private by default at the module level, pub открывает поле наружу; нет protected — видимость только public/private (и оттенки pub(crate)/pub(super)). exposes it; there's no protected — only public/private (with pub(crate)/pub(super) shades in between). МетодыMethodsimpl блок отдельно от struct; методы различают &self/&mut self/self по владению, associated-функции без self — аналог static. block lives separately from the struct; methods vary by &self/&mut self/self ownership, associated functions without self are the analogue of static.interview ИндексаторыIndexersтрейты the Index и and IndexMut — реальный языковой аналог operator[], IndexMut паникует вместо возврата ссылки на "нет значения" (в отличие от Option). traits — a real language analogue of operator[]; IndexMut panics instead of returning a "no value" reference (unlike Option).interview ПолиморфизмPolymorphismстатический через generics + монoморфизацию (compile-time, без накладных расходов) vs динамический через static via generics + monomorphization (compile-time, zero overhead) vs dynamic via dyn Trait (vtable, косвенный вызов, единый бинарный код для всех типов). (vtable, indirect calls, one shared binary for every type).interview Вложенные классыNested classesstruct можно объявить внутри модуля или функции; настоящей вложенности типа-в-типе как в Java нет — модули, а не классы, задают область видимости.a struct can be declared inside a module or a function; there's no true type-in-type nesting like Java's — modules, not classes, define scope. КонстантыConstantsconst внутри impl-блока — ассоциированная константа, вычисляется на этапе компиляции, в отличие от static нет фиксированного адреса в памяти. inside an impl block — an associated constant, evaluated at compile time; unlike static it has no fixed memory address. Копирование объектовCopying objectsтрейты the Clone (явное, (explicit, .clone()) и ) and Copy (неявное побитовое копирование для маленьких stack-типов) — по умолчанию присваивание перемещает (move), а не копирует. (implicit bitwise copy for small stack types) — by default, assignment moves rather than copies.interview Члены типаType memberstype-алиасы внутри трейта (associated types) — параметризуют трейт без generic-параметра на каждом вызове, как в Iterator::Item. aliases inside a trait (associated types) — parameterize a trait without a generic parameter at every call site, as in Iterator::Item.

Специфика RustRust-specific

то, чего нет в классическом ООПwhat classic OOP doesn't have
Трейты как интерфейсыTraits as interfacesdyn Trait (динамическая диспетчеризация через vtable, объект по ссылке/Box) против generic-параметра с trait bound (мономорфизация, инлайнинг, ноль накладных расходов, но раздувание кода). (dynamic dispatch via a vtable, an object behind a reference/Box) versus a generic parameter with a trait bound (monomorphization, inlining, zero overhead, but code bloat).interview Newtypestruct Meters(f64) — оборачивание типа в однополевую структуру ради типобезопасности и обхода orphan rule; композиция вместо наследования как основной способ переиспользования.struct Meters(f64) — wrapping a type in a single-field struct for type safety and to work around the orphan rule; composition over inheritance as the primary reuse mechanism.interview Derive-макросыDerive macros#[derive(Clone, Debug, PartialEq)] — генерируют шаблонные impl на этапе компиляции вместо базового класса с Object.equals/toString, как в Java/C#. — generate boilerplate impls at compile time instead of a base class with Object.equals/toString the way Java/C# would. Orphan ruleimpl трейта для типа разрешён только если трейт или тип определены в текущем крейте — не даёт двум крейтам конфликтующе реализовать один и тот же внешний трейт для одного и того же внешнего типа.implementing a trait for a type is allowed only if the trait or the type is defined in the current crate — prevents two crates from conflictingly implementing the same foreign trait for the same foreign type.interview

статус и как читать n/astatus and how to read n/a

Это каркас: 2 подраздела и 15 карточек зафиксированы, страницы ещё не написаны. Из 14 базовых концепций ООП в списке нет 4: перегрузки сигнатур, свойств, наследования и событий — в Rust для них нет реального языкового аналога даже по конвенции, поэтому отдельные карточки не заводились. Вместо них добавлен полиморфизм (generics vs dyn Trait). Оставшиеся карточки (конструкторы, деструкторы, индексаторы и другие) описывают механизм, который в Rust действительно существует, просто не в форме class/extends.This is a skeleton: 2 subsections and 15 cards are locked in, pages not yet written. 4 of the 14 baseline OOP concepts are missing from the list — signature overloading, properties, inheritance, and events — since Rust has no real language analogue for any of them even by convention, so no dedicated cards were created. Polymorphism (generics vs dyn Trait) was added in their place. The remaining cards (constructors, destructors, indexers, and others) describe a mechanism that genuinely exists in Rust, just not in class/extends form.