Back-end · formation gratuite
Rust Training
Learn Rust, the safe and performant programming language
- Avancé
- 12 chapitres
- Exemples de code
- 100 % gratuit
Introduction to Rust
Rust is a modern systems programming language developed by Mozilla. Rust combines C/C++ performance with memory safety, without a garbage collector.
🦀 What is Rust?
Rust is a compiled, statically typed, and memory-safe programming language. Rust guarantees memory safety at compile time without sacrificing performance.
💡 Why is Rust so popular?
- Memory safety - Guarantees memory safety at compile time, no segfaults
- Performance - Performance comparable to C/C++, without garbage collector
- Concurrency - Ownership system for safe concurrency
- Expressiveness - Modern syntax, pattern matching, traits
- Growth - Most loved language according to Stack Overflow for several years
- Ecosystem - Cargo (package manager), crates.io (libraries)
🚀 Why learn Rust?
Rust is an excellent choice for systems development and performant applications:
- ✅ Safety - No segfaults, no data races, safety guaranteed at compile time
- ✅ Performance - As fast as C/C++, without the risks
- ✅ Systems - Perfect for embedded systems, OS, browsers
- ✅ High demand - Used by Mozilla, Microsoft, Dropbox, Cloudflare
- ✅ Future - Rapidly growing language, adoption by major companies
- ✅ WebAssembly - Excellent for compiling to WebAssembly
📋 Prerequisites to learn Rust
To learn Rust effectively, it is recommended to have:
- ✅ Programming basics - Understanding basic concepts (variables, conditions, loops)
- ✅ Logic - Good understanding of programming logic
💡 Important note: To compile Rust code, you need Rustup (Rust installer). Install it from rustup.rs. You can use VS Code with the rust-analyzer extension, or RustRover (JetBrains IDE).
🎯 Rust Use Cases
Rust is used in many fields:
- Systems - Operating system development, drivers, firmware
- WebAssembly - Compilation to WebAssembly for the web
- Blockchain - Blockchain and smart contract development
- CLI tools - High-performance command-line tools
- Gaming - Game engines, rendering systems
📝 Basic Syntax
Rust syntax is modern and expressive. Rust uses braces {} to define code blocks and requires a semicolon ; at the end of statements.
// Premier programme Rust
fn main() {
println!("Bonjour, monde !");
let nom = "NiangProgrammeur";
let age = 25;
println!("Je m'appelle {} et j'ai {} ans", nom, age);
}
// Dans le terminal :
// cargo new mon_projet
// cargo run
💡 Important points about Rust syntax:
- Rust uses braces
{}to define code blocks - Comments use
//for a line or/* */for multiple lines - Mandatory semicolon
;at the end of each statement - Pattern matching - Powerful syntax with
match - Main function - Entry point:
fn main() - Conventions - Use snake_case for variables and functions
🔍 Detailed syntax example
Here is a complete example showing several aspects of Rust syntax:
// Définition d'une fonction : types des paramètres et du retour obligatoires
fn saluer(nom: &str) -> String {
format!("Bonjour, {} !", nom) // pas de ; : la valeur est renvoyée
}
fn main() {
let message = saluer("Awa");
println!("{}", message); // Bonjour, Awa !
// Les blocs sont des expressions
let mention = if 15 >= 14 { "bien" } else { "passable" };
println!("Mention {}", mention);
}
🔤 Variables
In Rust, variables are immutable by default. Use mut to make a variable mutable. Rust is a statically typed language.
fn main() {
// Les variables sont immuables par défaut
let nom = "Rust";
// nom = "Autre"; // erreur : impossible de modifier
// mut rend une variable modifiable
let mut compteur = 0;
compteur += 1;
// Type explicite (sinon déduit par le compilateur)
let age: u32 = 9;
let prix: f64 = 19.99;
let est_actif: bool = true;
// Constante : type obligatoire, valeur connue à la compilation
const PI: f64 = 3.14159;
// Masquage (shadowing) : redéclarer avec let
let valeur = "42";
let valeur: i32 = valeur.parse().unwrap();
println!("{} {} {} {} {}", nom, compteur, age, prix, est_actif);
println!("{} {}", PI, valeur + 1);
}
📌 Rules for variable names:
- Must start with a letter or underscore
_ - Can contain letters, numbers, and underscores
- Case sensitive
- Cannot be Rust keywords
- Convention: use
snake_casefor variables
📊 Data Types
Rust has several built-in data types. Here are the main ones:
fn main() {
// Entiers signés (i8 … i128) et non signés (u8 … u128)
let entier: i32 = -42;
let positif: u64 = 9_000_000_000;
// Flottants, booléens, caractères
let decimal: f64 = 3.14;
let vrai: bool = true;
let lettre: char = 'é'; // un caractère Unicode
// Chaînes : &str (texte fixe) et String (texte modifiable)
let fixe: &str = "Bonjour";
let mut texte = String::from("Bonjour");
texte.push_str(" Dakar");
// Tuple et tableau (taille fixe)
let point: (i32, i32) = (3, 4);
let notes: [u8; 3] = [12, 15, 18];
// Vecteur (taille variable)
let mut langages = vec!["Rust", "Go"];
langages.push("Python");
println!("{} {} {} {} {}", entier, positif, decimal, vrai, lettre);
println!("{} / {} / ({}, {})", fixe, texte, point.0, point.1);
println!("{:?} {:?} {}", notes, langages, langages.len());
}
📚 Rust Data Types:
- String, &str - Character strings
- i8, i16, i32, i64, i128 - Signed integers
- u8, u16, u32, u64, u128 - Unsigned integers
- f32, f64 - Decimal numbers
- bool - Booleans (true/false)
- char - Unicode character (4 bytes)
- Array, Vec - Arrays and vectors
🔢 Operators
Rust supports arithmetic, comparison, logical, and assignment operators:
fn main() {
let a = 17;
let b = 5;
// Opérateurs arithmétiques
println!("{}", a + b); // 22
println!("{}", a - b); // 12
println!("{}", a * b); // 85
println!("{}", a / b); // 3 (division entière)
println!("{}", a % b); // 2 (reste)
println!("{}", a as f64 / b as f64); // 3.4 (conversion explicite)
// Opérateurs de comparaison
println!("{} {} {}", a == b, a != b, a > b); // false true true
// Opérateurs logiques
let majeur = true;
let inscrit = false;
println!("{}", majeur && inscrit); // false
println!("{}", majeur || inscrit); // true
println!("{}", !majeur); // false
// Affectation combinée (variable mutable)
let mut total = 10;
total += 5; // 15
total *= 2; // 30
println!("{}", total);
// Pas de ++ en Rust : on écrit total += 1
}
🔀 Conditional Structures
Rust uses if, else if, and else for conditions. Rust also supports match for pattern matching.
fn main() {
let note = 14;
// if / else if / else (la condition doit être un bool)
if note >= 16 {
println!("Très bien");
} else if note >= 10 {
println!("Admis");
} else {
println!("Ajourné");
}
// if est une expression : il peut renvoyer une valeur
let statut = if note >= 10 { "admis" } else { "ajourné" };
println!("{}", statut);
// match : comparaison de motifs, tous les cas doivent être traités
match note {
16..=20 => println!("Mention très bien"),
14 | 15 => println!("Mention bien"),
10..=13 => println!("Passable"),
_ => println!("Insuffisant"),
}
// if let : réagir à une seule variante
let resultat: Option<u32> = Some(15);
if let Some(valeur) = resultat {
println!("Note trouvée : {}", valeur);
}
}
🔄 Loops
Rust offers several types of loops: loop, while, and for:
fn main() {
// for sur un intervalle
for i in 1..=5 {
println!("Tour {}", i);
}
// for sur une collection (par référence)
let langages = vec!["Rust", "Go", "Python"];
for langage in &langages {
println!("{}", langage);
}
// enumerate : index et valeur
for (i, langage) in langages.iter().enumerate() {
println!("{}. {}", i + 1, langage);
}
// while
let mut compteur = 3;
while compteur > 0 {
println!("Compte à rebours : {}", compteur);
compteur -= 1;
}
// loop : boucle infinie qui peut renvoyer une valeur
let mut n = 0;
let premier_multiple = loop {
n += 1;
if n % 7 == 0 {
break n; // sort de la boucle avec la valeur n
}
};
println!("{}", premier_multiple); // 7
// continue et itérateurs
for n in 1..=10 {
if n % 2 == 0 { continue; }
print!("{} ", n); // 1 3 5 7 9
}
let carres: Vec<i32> = (1..=3).map(|x| x * x).collect(); // [1, 4, 9]
println!("\n{:?}", carres);
}
⚙️ Functions
Functions in Rust are defined with fn. Rust supports functions with multiple return values via tuples.
// Fonction avec paramètres et valeur de retour
fn addition(a: i32, b: i32) -> i32 {
a + b
}
// Gérer une erreur possible avec Result
fn diviser(a: f64, b: f64) -> Result<f64, String> {
if b == 0.0 {
return Err(String::from("division par zéro"));
}
Ok(a / b)
}
// Renvoyer plusieurs valeurs avec un tuple
fn min_max(nombres: &[i32]) -> (i32, i32) {
(*nombres.iter().min().unwrap(), *nombres.iter().max().unwrap())
}
fn main() {
println!("{}", addition(3, 4)); // 7
match diviser(10.0, 0.0) {
Ok(r) => println!("Résultat : {}", r),
Err(e) => println!("Erreur : {}", e),
}
let (min, max) = min_max(&[4, 9, 1, 7]);
println!("min = {}, max = {}", min, max);
// Fermeture (closure) : fonction anonyme
let carre = |x: i32| x * x;
println!("{}", carre(5)); // 25
}
📋 Ownership & Borrowing
Rust's ownership system guarantees memory safety. Borrowing allows accessing data without owning it.
fn longueur(texte: &String) -> usize {
texte.len() // emprunt en lecture : on ne prend pas la propriété
}
fn ajouter_signature(texte: &mut String) {
texte.push_str(" — NiangProgrammeur"); // emprunt en écriture
}
fn main() {
// Chaque valeur a un seul propriétaire
let s1 = String::from("Bonjour");
let s2 = s1; // la propriété passe à s2 (déplacement)
// println!("{}", s1); // erreur : s1 n'est plus valide
println!("{}", s2);
// clone : copier explicitement la donnée
let s3 = s2.clone();
println!("{} {}", s2, s3);
// Emprunt immuable : plusieurs à la fois sont permis
let message = String::from("Apprendre Rust");
println!("{} caractères", longueur(&message));
// Emprunt mutable : un seul à la fois
let mut note = String::from("Cours terminé");
ajouter_signature(&mut note);
println!("{}", note);
// Les types simples (entiers, bool, char) sont copiés, pas déplacés
let a = 5;
let b = a;
println!("{} {}", a, b);
} // ici les String sont libérées automatiquement, sans ramasse-miettes
📦 Structs & Enums
Structs allow grouping data. Enums allow defining types with multiple variants.
// Struct : regroupe des données
struct Etudiant {
nom: String,
age: u8,
notes: Vec<f64>,
}
impl Etudiant {
// Constructeur (fonction associée)
fn new(nom: &str, age: u8) -> Self {
Etudiant { nom: nom.to_string(), age, notes: Vec::new() }
}
fn moyenne(&self) -> f64 {
if self.notes.is_empty() { return 0.0; }
self.notes.iter().sum::<f64>() / self.notes.len() as f64
}
}
// Enum : un type avec plusieurs variantes, qui peuvent porter des données
enum Paiement {
Especes,
Wave(String), // numéro de téléphone
Carte { numero: String },
}
fn decrire(p: &Paiement) -> String {
match p {
Paiement::Especes => "en espèces".to_string(),
Paiement::Wave(tel) => format!("par Wave ({})", tel),
Paiement::Carte { numero } => format!("par carte se terminant par {}", &numero[numero.len() - 4..]),
}
}
fn main() {
let mut awa = Etudiant::new("Awa", 20);
awa.notes.push(14.0);
awa.notes.push(16.0);
println!("{} ({} ans) : {:.1}", awa.nom, awa.age, awa.moyenne());
let p = Paiement::Wave(String::from("77 000 00 00"));
println!("Paiement {}", decrire(&p));
}
🏗️ Traits
Traits define shared behaviors. Traits are similar to interfaces in other languages.
// Un trait définit un comportement commun
trait Forme {
fn aire(&self) -> f64;
// Méthode avec une implémentation par défaut
fn decrire(&self) -> String {
format!("Forme d'aire {:.2}", self.aire())
}
}
struct Rectangle { largeur: f64, hauteur: f64 }
struct Cercle { rayon: f64 }
impl Forme for Rectangle {
fn aire(&self) -> f64 { self.largeur * self.hauteur }
}
impl Forme for Cercle {
fn aire(&self) -> f64 { std::f64::consts::PI * self.rayon * self.rayon }
fn decrire(&self) -> String { format!("Cercle de rayon {}", self.rayon) }
}
// Fonction générique : accepte tout type qui implémente Forme
fn afficher(f: &impl Forme) {
println!("{}", f.decrire());
}
fn main() {
let r = Rectangle { largeur: 4.0, hauteur: 3.0 };
let c = Cercle { rayon: 2.0 };
afficher(&r);
afficher(&c);
// Collection de types différents partageant le même trait
let formes: Vec<Box<dyn Forme>> = vec![Box::new(r), Box::new(c)];
let total: f64 = formes.iter().map(|f| f.aire()).sum();
println!("Aire totale : {:.2}", total);
}
// Traits de la bibliothèque standard : #[derive(Debug, Clone, PartialEq)]
📁 File Manipulation
Rust allows reading and writing files with the std::fs and std::io packages.
use std::fs::{self, OpenOptions};
use std::io::{self, BufRead, BufReader, Write};
fn main() -> io::Result<()> {
// Écrire dans un fichier (le crée ou l'écrase)
fs::write("notes.txt", "Awa : 15\nMoussa : 12\n")?;
// Ajouter du texte à la fin
let mut fichier = OpenOptions::new().append(true).open("notes.txt")?;
writeln!(fichier, "Fatou : 17")?;
// Lire tout le contenu
let contenu = fs::read_to_string("notes.txt")?;
println!("{}", contenu);
// Lire ligne par ligne
let lecteur = BufReader::new(fs::File::open("notes.txt")?);
for ligne in lecteur.lines() {
let ligne = ligne?;
if let Some((nom, note)) = ligne.split_once(" : ") {
println!("{} a obtenu {}/20", nom, note);
}
}
// Gérer l'absence d'un fichier sans arrêter le programme
match fs::read_to_string("absent.txt") {
Ok(texte) => println!("{}", texte),
Err(e) => println!("Impossible de lire le fichier : {}", e),
}
Ok(()) // l'opérateur ? propage les erreurs vers l'appelant
}
💡 Best practice: Use ? to propagate errors or unwrap() for fatal errors. Use Result to handle errors properly.
🎓 Next Steps
Congratulations! You now have a solid foundation in Rust.
✅ What you have learned:
- Rust syntax and variables
- Data types (String, i32, f64, bool)
- Operators and expressions
- Conditional structures (if, match)
- Loops (loop, while, for)
- Functions and tuples
- Ownership and borrowing
- Structs and enums
- Traits
- File manipulation
🚀 To go further:
- Advanced ownership - Lifetimes, borrowing rules
- Pattern matching - Advanced match expressions
- Traits - Defining and implementing traits
- Error handling - Result and Option
- Concurrency - Threads, channels, async/await