En bref. En Rust, &s[0..3] ne copie rien : c’est une fenêtre (une adresse et une longueur en octets) posée sur le tampon de s. Les indices comptent des octets, pas des caractères. Si la fenêtre coupe un caractère UTF-8 en deux, comme &s[0..1] sur « Ça va », le programme panique : byte index 1 is not a char boundary.
Le modèle en une phrase
Une slice est une fenêtre : une adresse et une longueur, posées sur les données de quelqu’un d’autre. Elle ne possède rien et se mesure en octets.
Le numéro 01 donnait le propriétaire, le numéro 02 la règle des lecteurs. La slice est le lecteur le plus courant : &str pour du texte, &[T] pour un tableau. Elle ne dit pas « ma chaîne », elle dit « à partir d’ici, tant d’octets ».
In short. In Rust, &s[0..3] copies nothing: it is a window (an address and a length in bytes) laid over s’s buffer. Indices count bytes, not characters. If the window splits a UTF-8 character in half, like &s[0..1] on “Ça va”, the program panics: byte index 1 is not a char boundary.
The model in one sentence
A slice is a window: an address and a length, laid over someone else’s data. It owns nothing and is measured in bytes.
Issue 01 gave the owner, issue 02 the readers’ rule. The slice is the most common reader: &str for text, &[T] for an array. It doesn’t say “my string”, it says “from here, this many bytes”.
fn main() {let s = String::from("Ça va");let mot = &s[0..3];let fin = &s[4..];println!("{mot} / {fin}");}
let s = String::from("Ça va");—spossède un tampon de 6 octets sur le tas : « Ç » en prend deux (UTF-8), les quatre autres caractères un chacun.sowns a 6-byte buffer on the heap: "Ç" takes two of them (UTF-8), the other four characters one each.let mot = &s[0..3];—motn'est pas une copie : c'est une fenêtre, une adresse dans le tampon desplus une longueur (3 octets). 16 octets sur la pile, aucune allocation.motis not a copy: it is a window, an address insides's buffer plus a length (3 bytes). 16 bytes on the stack, no allocation.let fin = &s[4..];—finest une deuxième fenêtre, qui commence 4 octets plus loin. Deux vues, toujours un seul tampon, toujours un seul propriétaire.finis a second window, starting 4 bytes further. Two views, still one buffer, still one owner.println!("{mot} / {fin}");— AfficheÇa / va. Les fenêtres sont des emprunts : tant qu'elles servent,sne peut être ni modifié ni libéré.PrintsÇa / va. Windows are borrows: as long as they are used,scan be neither modified nor freed.
La panique, telle que Rust l’écrit
fn main() {
let s = String::from("Ça va");
println!("{} caractères, {} octets", s.chars().count(), s.len());
let debut = &s[0..1];
println!("{debut}");
}5 caractères, 6 octets
thread 'main' panicked at src/main.rs:4:19:
end byte index 1 is not a char boundary; it is inside 'Ç' (bytes 0..2 of string)Le message dit tout le dessin : l’indice est un indice d’octet, et « Ç » occupe les octets 0 et 1. Une fenêtre qui s’arrête à 1 laisserait un demi-caractère, et une &str promet toujours de l’UTF-8 valide. Contrairement aux erreurs des deux articles précédents, celle-ci arrive à l’exécution : le compilateur ne connaît pas le contenu de la chaîne.
Les deux sorties sûres :
println!("{:?}", s.get(0..1)); // None : pas de panique
println!("{:?}", s.get(0..2)); // Some("Ç")
println!("{:?}", s.char_indices().collect::<Vec<_>>());None
Some("Ç")
[(0, 'Ç'), (2, 'a'), (3, ' '), (4, 'v'), (5, 'a')]char_indices donne les frontières valides : 0, 2, 3, 4, 5. Le 1 n’y est pas.
La preuve, mesurée
Le dessin affirme trois choses : une &str fait 16 octets, elle pointe dans le tampon de la String, et une deuxième fenêtre commence simplement plus loin. Le programme suivant les vérifie (rustc 1.100, édition 2024) :
fn main() {
let s = String::from("Bonjour");
let mot: &str = &s[0..3];
println!("{mot}");
println!("taille de &str : {} octets", std::mem::size_of::<&str>());
println!("taille de &String : {} octets", std::mem::size_of::<&String>());
println!("même tampon : {}", std::ptr::eq(s.as_ptr(), mot.as_ptr()));
let fin = &s[3..];
println!("{fin} commence {} octets plus loin", fin.as_ptr() as usize - s.as_ptr() as usize);
}Bon
taille de &str : 16 octets
taille de &String : 8 octets
même tampon : true
jour commence 3 octets plus loinUne &String fait 8 octets : une seule adresse, celle de la fiche de la String. Une &str en fait 16, parce qu’elle porte sa longueur : c’est ce qui lui permet de désigner un morceau.
La fenêtre est un emprunt
Une slice est une référence, donc la règle du numéro 02 s’applique : tant que la fenêtre sert, le propriétaire est figé.
fn premier_mot(s: &str) -> &str {
s.split(' ').next().unwrap_or("")
}
fn main() {
let mut s = String::from("Ça va");
let mot = premier_mot(&s);
s.clear();
println!("{mot}");
}error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable
--> src/main.rs:8:5
|
7 | let mot = premier_mot(&s);
| -- immutable borrow occurs here
8 | s.clear();
| ^^^^^^^^^ mutable borrow occurs here
9 | println!("{mot}");
| --- immutable borrow later used hereDans un langage sans cette règle, mot serait un index (0..2) qui ne correspond plus à rien après clear(). En Rust, la fenêtre est liée à la chaîne, et le compilateur refuse de vider ce qu’on regarde.
Le réflexe : &str en paramètre
Prendre &String en paramètre ferme la porte aux littéraux :
fn premier_mot(s: &String) -> &str {
s.split(' ').next().unwrap_or("")
}
fn main() {
println!("{}", premier_mot("bonjour tout le monde"));
}error[E0308]: mismatched types
--> src/main.rs:6:32
|
6 | println!("{}", premier_mot("bonjour tout le monde"));
| ----------- ^^^^^^^^^^^^^^^^^^^^^^^ expected `&String`, found `&str`
| |
| arguments to this function are incorrectAvec fn premier_mot(s: &str), la même fonction accepte tout : un littéral, &s (la &String se convertit seule en &str), et n’importe quel morceau &s[4..]. Même chose pour les tableaux : &[i32] plutôt que &Vec<i32>.
let v = vec![10, 20, 30, 40];
let milieu: &[i32] = &v[1..3]; // [20, 30]Ce que l’image cache
- Un littéral est déjà une slice.
"bonjour"est une&'static str: une fenêtre sur des octets rangés dans le binaire, qui ne sont jamais libérés. - Le
'staticet les durées de vie. La fenêtre ne doit jamais survivre au tampon. Quand une fonction renvoie une&strtirée de son paramètre, commepremier_mot, le compilateur relie les deux : c’est l’élision des durées de vie, le sujet du volume 2. &[T]ne connaît pas de « caractères ». La panique de frontière est propre àstr. Pour&v[1..9]sur unVecde 4 éléments, c’est une autre panique : range end index 9 out of range.- Le découpage est vérifié, pas gratuit.
&s[a..b]contrôle les bornes et les frontières à chaque appel. C’est le prix de la promesse « une&strest toujours de l’UTF-8 valide ».
Pour aller plus loin
- Le numéro 03 de The Rust Loop, Slices, va plus loin sur
&strcontreStringdans les signatures et sur les découpages de tableaux (lien en bas de page). - Articles précédents de la série : le move (E0382) et l’emprunt (E0502).
- The Rust Programming Language, chapitre 4.3 : The Slice Type
- The Rust Programming Language, chapitre 8.2 : Storing UTF-8 Encoded Text with Strings
The panic, as Rust writes it
fn main() {
let s = String::from("Ça va");
println!("{} caractères, {} octets", s.chars().count(), s.len());
let debut = &s[0..1];
println!("{debut}");
}5 caractères, 6 octets
thread 'main' panicked at src/main.rs:4:19:
end byte index 1 is not a char boundary; it is inside 'Ç' (bytes 0..2 of string)(5 characters, 6 bytes.)
The message tells the whole drawing: the index is a byte index, and “Ç” takes bytes 0 and 1. A window ending at 1 would leave half a character, and a &str always promises valid UTF-8. Unlike the errors of the two previous articles, this one happens at runtime: the compiler does not know the string’s contents.
The two safe ways out:
println!("{:?}", s.get(0..1)); // None: no panic
println!("{:?}", s.get(0..2)); // Some("Ç")
println!("{:?}", s.char_indices().collect::<Vec<_>>());None
Some("Ç")
[(0, 'Ç'), (2, 'a'), (3, ' '), (4, 'v'), (5, 'a')]char_indices gives the valid boundaries: 0, 2, 3, 4, 5. 1 is not among them.
The proof, measured
The drawing claims three things: a &str is 16 bytes, it points into the String’s buffer, and a second window simply starts further along. This program checks them (rustc 1.100, edition 2024):
fn main() {
let s = String::from("Bonjour");
let mot: &str = &s[0..3];
println!("{mot}");
println!("taille de &str : {} octets", std::mem::size_of::<&str>());
println!("taille de &String : {} octets", std::mem::size_of::<&String>());
println!("même tampon : {}", std::ptr::eq(s.as_ptr(), mot.as_ptr()));
let fin = &s[3..];
println!("{fin} commence {} octets plus loin", fin.as_ptr() as usize - s.as_ptr() as usize);
}Bon
taille de &str : 16 octets
taille de &String : 8 octets
même tampon : true
jour commence 3 octets plus loin(Size of &str: 16 bytes. Size of &String: 8 bytes. Same buffer: true. “jour” starts 3 bytes further.)
A &String is 8 bytes: a single address, that of the String’s record. A &str is 16, because it carries its length: that is what lets it designate a piece.
The window is a borrow
A slice is a reference, so the rule from issue 02 applies: as long as the window is used, the owner is frozen.
fn premier_mot(s: &str) -> &str {
s.split(' ').next().unwrap_or("")
}
fn main() {
let mut s = String::from("Ça va");
let mot = premier_mot(&s);
s.clear();
println!("{mot}");
}error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable
--> src/main.rs:8:5
|
7 | let mot = premier_mot(&s);
| -- immutable borrow occurs here
8 | s.clear();
| ^^^^^^^^^ mutable borrow occurs here
9 | println!("{mot}");
| --- immutable borrow later used hereIn a language without this rule, mot would be an index (0..2) that no longer matches anything after clear(). In Rust, the window is tied to the string, and the compiler refuses to empty what is being looked at.
The reflex: &str as a parameter
Taking &String as a parameter shuts the door on literals:
fn premier_mot(s: &String) -> &str {
s.split(' ').next().unwrap_or("")
}
fn main() {
println!("{}", premier_mot("bonjour tout le monde"));
}error[E0308]: mismatched types
--> src/main.rs:6:32
|
6 | println!("{}", premier_mot("bonjour tout le monde"));
| ----------- ^^^^^^^^^^^^^^^^^^^^^^^ expected `&String`, found `&str`
| |
| arguments to this function are incorrectWith fn premier_mot(s: &str), the same function accepts everything: a literal, &s (the &String converts to &str on its own), and any piece &s[4..]. Same for arrays: &[i32] rather than &Vec<i32>.
let v = vec![10, 20, 30, 40];
let milieu: &[i32] = &v[1..3]; // [20, 30]What the picture hides
- A literal is already a slice.
"bonjour"is a&'static str: a window onto bytes stored in the binary, never freed. 'staticand lifetimes. The window must never outlive the buffer. When a function returns a&strtaken from its parameter, likepremier_mot, the compiler ties the two together: that is lifetime elision, the topic of volume 2.&[T]knows nothing about “characters”. The boundary panic is specific tostr. For&v[1..9]on a 4-elementVec, it is a different panic: range end index 9 out of range.- Slicing is checked, not free.
&s[a..b]checks bounds and boundaries on every call. That is the price of the promise “a&stris always valid UTF-8”.
Going further
- Issue 03 of The Rust Loop, Slices, goes further on
&strversusStringin signatures and on slicing arrays (link at the bottom of the page). - Previous articles in the series: the move (E0382) and borrowing (E0502).
- The Rust Programming Language, chapter 4.3: The Slice Type
- The Rust Programming Language, chapter 8.2: Storing UTF-8 Encoded Text with Strings