Une fenêtre sur une donnée. Ni copie, ni possession.A window onto data. Neither copy nor ownership.
Le move déplace, l'emprunt prête la donnée entière. La slice est le troisième geste : emprunter une fenêtre — une portion contiguë — d'une collection, sans la copier ni la posséder. &str est une vue dans un String ; &[T] une vue dans un Vec. Ce n'est qu'un pointeur et une longueur : regarder une sous-partie ne coûte rien.The move relocates, the borrow lends the whole value. The slice is the third gesture: borrowing a window — a contiguous portion — of a collection, without copying or owning it. &str is a view into a String; &[T] a view into a Vec. It's just a pointer and a length: looking at a sub-part costs nothing.
let phrase = String::from("hello world"); let hello = &phrase[0..5]; // une VUE sur les 5 premiers octets let world = &phrase[6..11]; // une autre vue, même donnée sous-jacente println!("{hello} / {world}"); // hello / world — zéro copie, zéro alloc
La slice ne contient pas les caractères : elle pointe à l'intérieur du String, avec une longueur. Le buffer reste possédé par phrase — la vue n'en est qu'un emprunt cadré.The slice doesn't hold the characters: it points inside the String, with a length. The buffer stays owned by phrase — the view is just a framed borrow of it.
« Ai-je besoin de posséder cette donnée, ou seulement d'en regarder une partie ? » La réponse, presque toujours, est : regarder. Et alors la slice — &str, &[T] — est le bon type, pas le String ni le Vec possédés.'Do I need to own this data, or only to look at part of it?' The answer, almost always, is: look. And then the slice — &str, &[T] — is the right type, not the owned String or Vec.
Move, emprunt, slice : la trilogie de la possession. On sait déplacer une valeur, la prêter en entier, et maintenant en prêter une fenêtre. C'est le réflexe qui, à lui seul, désamorce la plupart des combats futurs contre le borrow checker — parce qu'on arrête de posséder ce qu'on voulait juste lire.Move, borrow, slice: the ownership trilogy. We can relocate a value, lend it whole, and now lend a window onto it. It's the reflex that, on its own, defuses most future fights with the borrow checker — because you stop owning what you only meant to read.