Обобщённые структуры и перечисления
Создавайте гибкие типы данных.
«Обобщённые структуры и перечисления» — бесплатный урок Learn Rust Coding на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Learn Rust Coding, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Learn Rust Coding содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Generic Data Structures
Just like functions, structs and enums can be generic over one or more types. This lets a single definition hold values of any type.
The standard library is built this way: Vec<T>, Option<T>, and Result<T, E> are all generic.
A Generic Struct
Declare the type parameter after the struct name, then use it for fields. Here Point stores two values of the same type T.
One definition now serves integer points, float points, and more.
struct Point<T> {
x: T,
y: T,
}Constructing Generic Structs
When you create an instance, the compiler infers T from the field values. Both fields must agree on the same type.
This program builds an integer point and a float point from the same struct.
struct Point<T> {
x: T,
y: T,
}
fn main() {
let a = Point { x: 1, y: 2 };
let b = Point { x: 1.5, y: 4.0 };
println!("{} {}", a.x, b.y);
}Mixed Type Parameters
Using two parameters lets fields differ. Pair<T, U> can hold an integer and a string at the same time.
Choose one parameter when fields must match, and several when they may vary.
struct Pair<T, U> {
first: T,
second: U,
}Methods on Generic Structs
To add methods, repeat the type parameter on the impl block: impl<T> Point<T>. The parameter after impl declares it; after the type name it applies it.
Here a getter returns a reference to the x field.
struct Point<T> {
x: T,
y: T,
}
impl<T> Point<T> {
fn x(&self) -> &T {
&self.x
}
}Methods With Bounds
You can write methods only for certain concrete types or for types meeting a bound. This impl applies just to Point<f64>.
So dist_from_origin exists on float points but not integer points.
struct Point<T> { x: T, y: T }
impl Point<f64> {
fn dist_from_origin(&self) -> f64 {
(self.x * self.x + self.y * self.y).sqrt()
}
}A Generic Enum
Enums are generic too. Each variant can carry generic data. This mirrors the standard Option, which is either Some(T) or None.
Defining your own helps you see how the library type works.
enum Maybe<T> {
Just(T),
Nothing,
}Two Parameters in an Enum
Result uses two parameters so the success and error values can differ. Here is a simplified version.
Multiple type parameters in enums power flexible error handling across the ecosystem.
enum Either<L, R> {
Left(L),
Right(R),
}Matching Generic Enums
You pattern match generic enums exactly like concrete ones. The bound payload becomes a binding inside the arm.
This program unwraps a custom Maybe and prints the contained value or a fallback.
enum Maybe<T> { Just(T), Nothing }
fn main() {
let m: Maybe<i32> = Maybe::Just(5);
match m {
Maybe::Just(n) => println!("got {}", n),
Maybe::Nothing => println!("empty"),
}
}Wrapping a Value
A common pattern is a wrapper struct with one field of type T plus helper methods. Here Wrapper stores and returns any value.
This is the foundation of newtype patterns and smart-pointer-like types.
struct Wrapper<T> { inner: T }
impl<T> Wrapper<T> {
fn new(v: T) -> Self {
Wrapper { inner: v }
}
}
fn main() {
let w = Wrapper::new("hi");
println!("{}", w.inner);
}No Runtime Overhead
Generic structs and enums are also monomorphized. Point<i32> and Point<f64> become two distinct, fully specialized types after compilation.
There is no hidden indirection or tag for the generic type itself.
Quick Check
Test your understanding of generic structs and enums.
Recap
Structs and enums declare type parameters after their name and use them in fields and variants, enabling reusable containers like Option and Result.
Methods repeat parameters on impl<T>, and you can write specialized impl blocks for concrete types. Everything is monomorphized for zero overhead.
Часто задаваемые вопросы
Урок «Обобщённые структуры и перечисления» бесплатный?
Да — полный текст урока «Обобщённые структуры и перечисления» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Learn Rust Coding, подпишись на CoddyKit PRO. Курс Learn Rust Coding содержит 4 уроков всего.
Чему я научусь в уроке «Обобщённые структуры и перечисления»?
Создавайте гибкие типы данных. Ты практикуешь Learn Rust Coding с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Learn Rust Coding?
Предыдущий опыт не требуется. Learn Rust Coding на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.
Сколько времени занимает урок «Обобщённые структуры и перечисления»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Learn Rust Coding?
Да. Каждый урок Learn Rust Coding включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Обобщённые функции
- Обобщённые структуры и перечисления
- Ограничения трейтов
- Предложения where и несколько ограничений