Agrandir et réduire
Insérez, supprimez et redimensionnez.
Agrandir et réduire est une leçon Learn Rust Coding gratuite sur CoddyKit. Ceci est la leçon 3 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.
Vectors Can Change Size
A key feature of vectors is that they change size at runtime. You can add elements when you have more data and remove them when you no longer need them.
Every size change requires the vector to be declared mut.
Growing With push
The push method adds a single element to the end, growing the vector by one. This is the most common way to grow.
Below the vector grows from length 0 to length 3.
fn main() {
let mut v = Vec::new();
v.push("a");
v.push("b");
v.push("c");
println!("len = {}", v.len());
}Removing With pop
The pop method removes and returns the last element wrapped in an Option. You get Some(value) normally, or None if the vector was already empty.
This shrinks the vector by one.
fn main() {
let mut v = vec![1, 2, 3];
let last = v.pop();
println!("popped {:?}", last);
println!("now {:?}", v);
}Inserting in the Middle
The insert method places a value at a given index and shifts later elements to the right. The index must be from 0 up to the current length.
Here we slip 99 into position 1.
fn main() {
let mut v = vec![10, 20, 30];
v.insert(1, 99);
println!("{:?}", v);
}Removing by Index
The remove method deletes the element at an index, returns it, and shifts later elements left to fill the gap.
Beware: removing an index that does not exist panics.
fn main() {
let mut v = vec![10, 20, 30];
let gone = v.remove(0);
println!("removed {}", gone);
println!("{:?}", v);
}Fast Removal With swap_remove
When order does not matter, swap_remove is faster. It moves the last element into the removed slot instead of shifting everything.
This changes the order but avoids the cost of shifting.
fn main() {
let mut v = vec![1, 2, 3, 4];
let x = v.swap_remove(0);
println!("took {}", x);
println!("{:?}", v);
}Clearing Everything
The clear method removes all elements at once, leaving an empty vector with length 0. The vector keeps its allocated capacity for reuse.
It is handy when you want to refill a vector from scratch.
fn main() {
let mut v = vec![1, 2, 3];
v.clear();
println!("empty? {}", v.is_empty());
}Truncating to a Length
The truncate method shortens a vector to a chosen length by dropping the extra elements at the end. If the vector is already shorter, nothing happens.
Here we keep only the first two elements.
fn main() {
let mut v = vec![1, 2, 3, 4, 5];
v.truncate(2);
println!("{:?}", v);
}Joining With extend
The extend method appends every item from another collection. It is like calling push for each element in one step.
Below a second list is added to the end of the first.
fn main() {
let mut v = vec![1, 2];
v.extend(vec![3, 4, 5]);
println!("{:?}", v);
}Keeping Only Some With retain
The retain method keeps only the elements that pass a test, removing the rest in place. You give it a closure that returns a bool.
Here we keep only the even numbers.
fn main() {
let mut v = vec![1, 2, 3, 4, 5, 6];
v.retain(|n| n % 2 == 0);
println!("{:?}", v);
}Sorting Elements
The sort method reorders elements from smallest to largest in place. It does not change the length, just the arrangement.
Sorting needs the vector to be mut.
fn main() {
let mut v = vec![3, 1, 4, 1, 5];
v.sort();
println!("{:?}", v);
}Quick Check
Test your understanding of growing and shrinking vectors.
Recap
You grew vectors with push, insert, and extend, and shrank them with pop, remove, swap_remove, clear, and truncate.
You also filtered with retain and ordered with sort. Next you will store structs inside vectors.
Questions Fréquemment Posées
La leçon « Agrandir et réduire » est-elle gratuite ?
Oui — le texte complet de « Agrandir et réduire » 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 « Agrandir et réduire » ?
Insérez, supprimez et redimensionnez. 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 3 sur 4.
Combien de temps prend la leçon « Agrandir et réduire » ?
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
- Créer et remplir des vecteurs
- Indexer et parcourir
- Agrandir et réduire
- Vecteurs de structures