| name | rust |
| description | Guide complet du langage Rust — ownership, borrowing, lifetimes, traits, async, unsafe, cargo, patterns et écosystème. En français. |
Rust — Guide Complet (Français)
Langage système sans garbage collector, mémoire sûre, performances natives. Édition 2021+.
1. Installation et Outils
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
rustc --version
cargo --version
rustup update
rustup component add clippy rustfmt
cargo new mon_projet
cargo build --release
cargo run
cargo test
cargo doc --open
cargo fmt
cargo clippy
2. Types et Variables
let x: i32 = 42;
let y: u64 = 100;
let z: f64 = 3.14159;
let actif: bool = true;
let c: char = '🦀';
let a = 42;
let b = 3.14;
let mut compteur = 0;
compteur += 1;
const MAX_POINTS: u32 = 100_000;
let tup: (i32, f64, u8) = (500, 6.4, 1);
let (x, y, z) = tup;
let premier = tup.0;
let arr: [i32; 5] = [1, 2, 3, 4, 5];
let zeros = [0; 100];
let premier = arr[0];
let mut vec: Vec<i32> = Vec::new();
vec.push(1);
vec.push(2);
let vec2 = vec![1, 2, 3, 4, 5];
let troisieme = vec2[2];
let slice: &[i32] = &vec2[1..4];
let s: &str = "Hello";
let mut s2: String = String::from("Hello");
s2.push_str(" World");
let s3 = format!("{} {}", s, "Rust");
use std::collections::HashMap;
let mut scores = HashMap::new();
scores.insert(String::from("Bleu"), 10);
scores.insert(String::from("Rouge"), 50);
let score = scores.get("Bleu").copied().unwrap_or(0);
3. Ownership, Borrowing, Lifetimes
let s1 = String::from("hello");
let s2 = s1;
let s3 = s2.clone();
let x = 5;
let y = x;
println!("{}", x);
fn calculer_longueur(s: &String) -> usize {
s.len()
}
let s = String::from("hello");
let len = calculer_longueur(&s);
println!("{}", s);
fn ajouter(s: &mut String) {
s.();
}
= ::();
(& s);
<>(x: & , y: & ) & {
x.() > y.() { x } { y }
}
<> {
partie: & ,
}
4. Fonctions et Closures
fn additionner(a: i32, b: i32) -> i32 {
return a + b;
}
fn multiplier(a: i32, b: i32) -> i32 {
a * b
}
fn afficher(message: &str) {
println!("{}", message);
}
let doubler = |x: i32| -> i32 { x * 2 };
let ajouter = |a, b| a + b;
let mut compteur = 0;
let mut incrementer = || {
compteur += 1;
compteur
};
fn appliquer<F>(f: F, x: i32) -> i32
where
F: Fn(i32) -> ,
{
(x)
}
= (|x| x + , );
5. Structs, Enums, Traits
struct Utilisateur {
nom: String,
email: String,
age: u32,
actif: bool,
}
let alice = Utilisateur {
email: String::from("alice@exemple.com"),
nom: String::from("Alice"),
age: 30,
actif: true,
};
struct Couleur(i32, i32, i32);
let noir = Couleur(0, 0, 0);
struct Marqueur;
impl Utilisateur {
fn nouveau(nom: String, email: String) -> Self {
Self { nom, email, age: 0, actif: true }
}
fn saluer(&self) -> String {
format!(, .nom)
}
(& ) {
.age += ;
}
() {
::()
}
}
<T, E> {
(T),
(E),
}
<T> {
(T),
,
}
{
Quitter,
Deplacer { x: , y: },
(),
(, , ),
}
(msg: Message) {
msg {
Message::Quitter => (),
Message::Deplacer { x, y } => (, x, y),
Message::(texte) => (, texte),
Message::(r, g, b) => {
(, r, g, b)
}
}
}
::(texte) = msg {
(, texte);
}
{
(&) ;
(&) {
::()
}
}
{
(&) {
(, .nom, .email)
}
}
<T: Resumable>(item: &T) {
(, item.());
}
(item: & Resumable) {
(, item.());
}
{
x: ,
y: ,
}
6. Gestion d'Erreurs
use std::fs::File;
use std::io::{self, Read};
fn lire_fichier(chemin: &str) -> Result<String, io::Error> {
let mut fichier = File::open(chemin)?;
let mut contenu = String::new();
fichier.read_to_string(&mut contenu)?;
Ok(contenu)
}
match lire_fichier("test.txt") {
Ok(contenu) => println!("{}", contenu),
Err(e) => eprintln!("Erreur : {}", e),
}
let contenu = lire_fichier("test.txt").unwrap();
let contenu = lire_fichier("test.txt").expect("Fichier introuvable");
fn trouver_element(liste: &[i32], cible: ) <> {
liste.().(|&x| x == cible)
}
(&[, , ], ) {
(index) => (, index),
=> (),
}
7. Itérateurs et Closures
let nombres = vec![1, 2, 3, 4, 5];
let carres: Vec<i32> = nombres.iter().map(|x| x * x).collect();
let pairs: Vec<&i32> = nombres.iter().filter(|&&x| x % 2 == 0).collect();
let somme = nombres.iter().fold(0, |acc, x| acc + x);
let resultat: Vec<i32> = (1..=100)
.filter(|x| x % 3 == 0)
.map(|x| x * 2)
.take(5)
.collect();
let iter = (0..).(|x| x * x).(|x| x % == );
iter.() {
(, x);
}
8. Smart Pointers
let b = Box::new(5);
println!("b = {}", b);
use std::rc::Rc;
let a = Rc::new(String::from("hello"));
let b = Rc::clone(&a);
let c = Rc::clone(&a);
println!("Références : {}", Rc::strong_count(&a));
use std::sync::Arc;
use std::thread;
let a = Arc::new(vec![1, 2, 3]);
let a_clone = Arc::clone(&a);
thread::spawn(move || {
println!("{:?}", a_clone);
});
use std::cell::RefCell;
let x = RefCell::new(42);
*x.() += ;
(, x.());
= Rc::(RefCell::());
9. Concurrence
use std::thread;
use std::sync::{Arc, Mutex, mpsc};
use std::time::Duration;
let handle = thread::spawn(|| {
for i in 1..=5 {
println!("Thread : {}", i);
thread::sleep(Duration::from_millis(10));
}
});
for i in 1..=3 {
println!("Principal : {}", i);
thread::sleep(Duration::from_millis(10));
}
handle.join().unwrap();
let compteur = Arc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..10 {
let compteur = Arc::clone(&compteur);
let handle = thread::spawn(move || {
= compteur.().();
*num += ;
});
handles.(handle);
}
handles {
handle.().();
}
(, *compteur.().());
(tx, rx) = mpsc::();
thread::( || {
tx.().();
tx.().();
});
rx {
(, recu);
}
10. Async/Await avec Tokio
use tokio;
#[tokio::main]
async fn main() {
let (r1, r2) = tokio::join!(
tache_1(),
tache_2(),
);
tokio::select! {
resultat = tache_longue() => println!("Tâche longue : {}", resultat),
_ = tokio::time::sleep(Duration::from_secs(5)) => println!("Timeout !"),
}
}
async fn tache_1() -> String {
tokio::time::sleep(Duration::from_secs(1)).await;
String::from("Tâche 1 terminée")
}
async fn tache_2() -> String {
String::from("Tâche 2 immédiate")
}
async fn requete_http() -> Result<(), reqwest::Error> {
let = reqwest::Client::();
= client
.()
.()
.?
.json::<serde_json::Value>()
.?;
(, reponse);
(())
}
11. Tests
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_additionner() {
assert_eq!(additionner(2, 2), 4);
assert_ne!(additionner(2, 2), 5);
}
#[test]
#[should_panic(expected = "division par zéro")]
fn test_division_zero() {
diviser(10, 0);
}
#[test]
#[ignore]
fn test_lent() {
}
}
12. Unsafe Rust
let mut x = 5;
let r1 = &x as *const i32;
let r2 = &mut x as *mut i32;
unsafe {
println!("r1: {}", *r1);
*r2 += 1;
}
unsafe fn dangereux() {
}
extern "C" {
fn abs(input: i32) -> i32;
}
unsafe {
println!("Valeur absolue de -3 : {}", abs(-3));
}
#[no_mangle]
pub extern "C" fn appel_depuis_c() {
println!("Appelé depuis C !");
}
13. Écosystème Essentiel
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio = { version = "1", features = ["full"] }
reqwest = { version = "0.12", features = ["json"] }
axum = "0.7"
sqlx = { version = "0.7", features = ["sqlite"] }
clap = { version = "4", features = ["derive"] }
rayon = "1"
anyhow = "1"
thiserror = "1"
tracing = "0.1"
rand = "0.8"
Références