Fonctions génériques
Paramétrez le comportement par type.
Fonctions génériques est une leçon Learn Rust Coding gratuite sur CoddyKit. Ceci est la leçon 1 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.
Why Generic Functions
Generic functions let you write one function that works with many types instead of copying code per type. Rust replaces the placeholder type at compile time.
Imagine writing one largest for integers and another for chars. Generics collapse those into a single definition with no runtime cost.
Type Parameters
A generic function declares a type parameter inside angle brackets after the name. The name T is a convention, but any CamelCase identifier works.
The parameter can then appear in arguments and the return type, standing in for whatever concrete type the caller uses.
fn first<T>(pair: (T, T)) -> T {
pair.0
}A Simple Identity Function
This program defines a generic echo that returns its argument unchanged. It is called once with an integer and once with a string slice.
The compiler generates a separate concrete version for each type that is actually used.
fn echo<T>(value: T) -> T {
value
}
fn main() {
println!("{}", echo(42));
println!("{}", echo("hi"));
}Monomorphization
Rust uses monomorphization: at compile time it produces a specialized copy of the function for every concrete type used. There is no boxing or virtual dispatch.
The result is generic code that runs as fast as hand-written, type-specific code.
Generics Need Constraints
Inside a generic function you can only use operations that every possible type supports. A bare T cannot be added, compared, or printed.
This code fails to compile because T might not implement comparison. We will fix it with a trait bound next.
fn larger<T>(a: T, b: T) -> T {
if a > b { a } else { b }
}Adding a Trait Bound
To compare values we constrain T with PartialOrd. The bound promises the type supports the > operator.
We also add Copy so the values can be returned without moving issues for simple types like integers.
fn larger<T: PartialOrd + Copy>(a: T, b: T) -> T {
if a > b { a } else { b }
}Calling the Bounded Function
Now the function works for any type implementing both traits. Integers and floats both satisfy PartialOrd + Copy.
The same source code, monomorphized into two versions, prints results for each call.
fn larger<T: PartialOrd + Copy>(a: T, b: T) -> T {
if a > b { a } else { b }
}
fn main() {
println!("{}", larger(3, 9));
println!("{}", larger(2.5, 1.0));
}Multiple Type Parameters
A function can declare several type parameters. Each is independent, so the two arguments may have different types.
Here pair accepts any T and any U and returns them as a tuple.
fn pair<T, U>(a: T, b: U) -> (T, U) {
(a, b)
}Printing Generic Values
To print a generic value with {} the type must implement Display. We add that bound so any printable type can be passed.
This labels a value and returns it, demonstrating a bound used purely for formatting.
use std::fmt::Display;
fn announce<T: Display>(label: &str, value: T) {
println!("{}: {}", label, value);
}
fn main() {
announce("count", 7);
announce("name", "Ada");
}Turbofish Syntax
Sometimes the compiler cannot infer T from arguments alone. The turbofish ::<Type> lets you specify it explicitly at the call site.
It is most common with methods like parse and collect where the return type is ambiguous.
fn main() {
let n = "42".parse::<i32>().unwrap();
println!("{}", n + 1);
}Generics Over References
Generic parameters work with references too. Constraining by reference avoids requiring Copy when you only need to read values.
This longest_str-style helper borrows two slices and returns one without taking ownership.
fn pick<'a, T: PartialOrd>(a: &'a T, b: &'a T) -> &'a T {
if a > b { a } else { b }
}Quick Check
Test your understanding of generic functions in Rust.
Recap
Generic functions use type parameters in angle brackets to work across many types with zero runtime cost via monomorphization.
Operations on a generic type require trait bounds like PartialOrd, Copy, or Display. Use the turbofish when inference cannot determine the type.
Questions Fréquemment Posées
La leçon « Fonctions génériques » est-elle gratuite ?
Oui — le texte complet de « Fonctions 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 « Fonctions génériques » ?
Paramétrez le comportement par type. 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 1 sur 4.
Combien de temps prend la leçon « Fonctions 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