Structures et énumérés génériques
Construisez des types de données flexibles.
Structures et énumérés génériques est une leçon Learn Rust Coding gratuite sur CoddyKit. Ceci est la leçon 2 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Learn Rust Coding, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Learn Rust Coding comprend 4 leçons au total.
Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.
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.
Questions Fréquemment Posées
La leçon « Structures et énumérés génériques » est-elle gratuite ?
Oui — le texte complet de « Structures et énumérés génériques » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Learn Rust Coding, passe à CoddyKit PRO. Le cours Learn Rust Coding comprend 4 leçons au total.
Qu'est-ce que j'apprendrai dans « Structures et énumérés génériques » ?
Construisez des types de données flexibles. Tu pratiques Learn Rust Coding avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.
Dois-je avoir de l'expérience pour commencer Learn Rust Coding ?
Aucune expérience préalable n'est requise. Learn Rust Coding sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 2 sur 4.
Combien de temps prend la leçon « Structures et énumérés génériques » ?
La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.
Peux-tu écrire et exécuter du code dans cette leçon Learn Rust Coding ?
Oui. Chaque leçon Learn Rust Coding inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.
Toutes les leçons de ce cours
- Fonctions génériques
- Structures et énumérés génériques
- Contraintes de traits
- Clauses where et contraintes multiples