« consider cloning the value if the performance cost is acceptable » : clone, emprunt et Cow en Rust "consider cloning the value if the performance cost is acceptable": clone, borrowing and Cow in Rust

En Rust, .clone() sur une String alloue un nouveau tampon et y copie le texte. C'est la correction que rustc propose après une erreur E0382, mais c'est souvent un emprunt qu'il fallait écrire : une fonction qui ne fait que lire prend un &str et n'alloue rien. Ce que ça implique : la frontière entre Copy et Clone, un Vec cloné qui alloue mille fois, Arc::clone qui ne copie rien, et Cow, qui reste un emprunt tant qu'il n'y a rien à modifier.In Rust, .clone() on a String allocates a new buffer and copies the text into it. It is the fix rustc suggests after an E0382 error, but what was needed is often a borrow: a function that only reads takes a &str and allocates nothing. What follows from it: the line between Copy and Clone, a cloned Vec that allocates a thousand times, Arc::clone that copies nothing, and Cow, which stays a borrow as long as nothing has to change.

AuteurAuthor
Ludovic Cleuet
ThèmeTopic
PerformancePerformance
PubliéPublished

En bref. Quand une valeur est utilisée après avoir été déplacée, rustc propose de la cloner, « si le coût est acceptable ». Ce coût est concret : cloner une String alloue un tampon et copie le texte. Souvent, la fonction n’avait besoin que de lire, et un emprunt suffisait. Et quand une fonction modifie parfois son entrée, Cow permet de ne payer l’allocation que ces fois-là.

Le modèle en une phrase

Une String possède un tampon dans le tas. La déplacer change le propriétaire du tampon, la cloner en alloue un second, l’emprunter n’en crée aucun. Cow est un emprunt qui ne devient une copie que lorsqu’il faut écrire.

L’animation compte les tampons : d’abord pour un déplacement, un clone et un emprunt, puis pour une fonction qui rend un Cow.

In short. When a value is used after being moved, rustc suggests cloning it, “if the performance cost is acceptable”. That cost is concrete: cloning a String allocates a buffer and copies the text. Often the function only needed to read, and a borrow was enough. And when a function sometimes modifies its input, Cow lets you pay the allocation only those times.

The model in one sentence

A String owns a buffer on the heap. Moving it changes the owner of the buffer, cloning it allocates a second one, borrowing it creates none. Cow is a borrow that only becomes a copy when something has to be written.

The animation counts the buffers: first for a move, a clone and a borrow, then for a function that returns a Cow.

let nom = String::from("Ada");
Une String, un tamponOne String, one bufferqui possède quoi, et combien de tamponswho owns what, and how many buffersla pilethe stacknom : Stringle tasthe heap"Ada"tampons dans le tas : 1buffers on the heap: 1possèdeownsemprunteborrowsdéplacé, inutilisablemoved, unusablesortie du programmeprogram outputrien n’est encore affichénothing printed yetsorties : rustc 1.100output: rustc 1.100une String : trois champs sur la pile, le texte dans le tasa String: three fields on the stack, the text on the heapnom possède un tampon dans le tasnom owns a buffer on the heap
  1. nom est une String. Sur la pile, elle tient en trois champs : un pointeur, une longueur, une capacité. Le texte lui-même est dans un tampon du tas, que nom possède. Créer cette String a coûté une allocation.nom is a String. On the stack, it is three fields: a pointer, a length, a capacity. The text itself lives in a heap buffer, which nom owns. Creating this String cost one allocation.
  2. longueur prend une String par valeur : l'appel déplace nom dans le paramètre s. Aucune copie, le tampon change seulement de propriétaire. Mais nom n'est plus utilisable, et la ligne suivante est refusée : E0382. L'aide du compilateur propose nom.clone(), if the performance cost is acceptable.longueur takes a String by value: the call moves nom into the parameter s. No copy, the buffer only changes owner. But nom can no longer be used, and the next line is rejected: E0382. The compiler's help suggests nom.clone(), if the performance cost is acceptable.
  3. Avec nom.clone(), le programme compile. Le clone alloue un second tampon et y copie les octets ; c'est cette copie que longueur reçoit, lit, puis détruit. Le compteur passe à deux allocations, alors que la fonction n'avait besoin que de lire.With nom.clone(), the program compiles. The clone allocates a second buffer and copies the bytes into it; that copy is what longueur receives, reads, then destroys. The counter goes to two allocations, even though the function only needed to read.
  4. L'autre correction change la fonction : longueur_ref prend un &str. s est alors un emprunt, un pointeur et une longueur qui désignent le tampon de nom. Rien n'est alloué, rien n'est copié, et nom reste utilisable. Le compteur reste à un.The other fix changes the function: longueur_ref takes a &str. s is then a borrow, a pointer and a length that designate the buffer of nom. Nothing is allocated, nothing is copied, and nom stays usable. The counter stays at one.
Une String possède un tampon dans le tas. La passer par valeur la déplace, et la réutiliser donne E0382. .clone() alloue un second tampon et y copie le texte ; emprunter avec &str n’alloue rien et laisse la valeur utilisable.A String owns a buffer on the heap. Passing it by value moves it, and using it again gives E0382. .clone() allocates a second buffer and copies the text into it; borrowing with &str allocates nothing and leaves the value usable.

Ce que le compilateur propose

Le point de départ est une erreur que tout le monde rencontre. Une fonction prend une String, et l’appelant veut encore s’en servir ensuite :

fn afficher(s: String) {
    println!("bonjour {s}");
}

fn main() {
    let nom = String::from("Ada");
    afficher(nom);
    println!("{nom}");
}
error[E0382]: borrow of moved value: `nom`
 --> deplace.rs:8:16
  |
6 |     let nom = String::from("Ada");
  |         --- move occurs because `nom` has type `String`, which does not implement the `Copy` trait
7 |     afficher(nom);
  |              --- value moved here
8 |     println!("{nom}");
  |                ^^^ value borrowed here after move
  |
note: consider changing this parameter type in function `afficher` to borrow instead if owning the value isn't necessary
 --> deplace.rs:1:16
  |
1 | fn afficher(s: String) {
  |    --------    ^^^^^^ this parameter takes ownership of the value
  |    |
  |    in this function
help: consider cloning the value if the performance cost is acceptable
  |
7 |     afficher(nom.clone());
  |                 ++++++++

Le message contient deux corrections, et elles ne se valent pas.

  • La note, en premier : changer le paramètre pour qu’il emprunte, if owning the value isn’t necessary. Elle demande de modifier la fonction.
  • L’aide, en dernier : ajouter .clone(), if the performance cost is acceptable. Elle tient en huit caractères, au point d’appel, avec le correctif prêt à copier.

La seconde est la plus facile à appliquer, donc la plus appliquée. Le reste de l’article mesure ce qu’elle coûte.

Ce que coûte un clone

Pour le voir, on remplace l’allocateur global par un allocateur qui compte ses appels, puis on mesure les deux écritures :

use std::alloc::{GlobalAlloc, Layout, System};
use std::sync::atomic::{AtomicUsize, Ordering};

struct Compteur;
static ALLOCS: AtomicUsize = AtomicUsize::new(0);

unsafe impl GlobalAlloc for Compteur {
    unsafe fn alloc(&self, l: Layout) -> *mut u8 {
        ALLOCS.fetch_add(1, Ordering::Relaxed);
        unsafe { System.alloc(l) }
    }
    unsafe fn dealloc(&self, p: *mut u8, l: Layout) {
        unsafe { System.dealloc(p, l) }
    }
}

#[global_allocator]
static A: Compteur = Compteur;

fn allocs() -> usize {
    ALLOCS.load(Ordering::Relaxed)
}

fn par_valeur(s: String) -> usize {
    s.len()
}

fn par_emprunt(s: &str) -> usize {
    s.len()
}

fn main() {
    let nom = String::from("Ada Lovelace");

    let avant = allocs();
    let n = par_valeur(nom.clone());
    let clone = allocs() - avant;

    let avant = allocs();
    let m = par_emprunt(&nom);
    let emprunt = allocs() - avant;

    let copie = nom.clone();
    let meme = nom.as_ptr() == copie.as_ptr();

    println!("clone   : {clone} allocation");
    println!("emprunt : {emprunt} allocation");
    println!("longueurs : {n} et {m}");
    println!("même tampon : {meme}");
}
clone   : 1 allocation
emprunt : 0 allocation
longueurs : 12 et 12
même tampon : false

Les deux fonctions rendent le même résultat. La première a demandé de la mémoire au système, copié douze octets, puis libéré cette mémoire à la fin de l’appel. La seconde a reçu un pointeur et une longueur.

La dernière ligne montre ce qu’est un clone : nom et copie ont le même contenu, mais pas le même tampon.

       pile                       tas

nom    ┌ ptr ──────────────────▶ ┌──────────────┐
       │ len 12                  │ Ada Lovelace │
       └ cap 12                  └──────────────┘

copie  ┌ ptr ──────────────────▶ ┌──────────────┐   nom.clone() :
       │ len 12                  │ Ada Lovelace │   une allocation,
       └ cap 12                  └──────────────┘   douze octets copiés

s      ┌ ptr ──────────▶ (le tampon de nom)         &nom :
       └ len 12                                     rien d'alloué

Copy et Clone : où passe la frontière

Certains types se copient sans qu’on l’écrive, d’autres non. La règle tient à ce que la valeur possède.

#[derive(Debug, Clone, Copy)]
struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let n = 5;
    let m = n;
    println!("{n} {m}");

    let p = Point { x: 1, y: 2 };
    let q = p;
    println!("{p:?} {q:?}");

    let s = String::from("Ada");
    println!("String : {} octets sur la pile, {} dans le tas", std::mem::size_of_val(&s), s.len());
}
5 5
Point { x: 1, y: 2 } Point { x: 1, y: 2 }
String : 24 octets sur la pile, 3 dans le tas

Un i32 ou un Point tient tout entier sur la pile. Le copier, c’est dupliquer quelques octets : le langage le fait implicitement, et les deux variables restent utilisables. Ces types sont Copy.

Une String fait 24 octets sur la pile, mais ces octets ne sont que la poignée d’un tampon. Les dupliquer donnerait deux propriétaires au même tampon, donc deux libérations. Le langage refuse cette copie implicite : il déplace. Et il refuse aussi qu’on la force :

#[derive(Clone, Copy)]
struct Client {
    nom: String,
}
error[E0204]: the trait `Copy` cannot be implemented for this type
 --> copystr.rs:2:8
  |
1 | #[derive(Clone, Copy)]
  |                 ---- in this derive macro expansion
2 | struct Client {
  |        ^^^^^^
3 |     nom: String,
  |     ----------- this field does not implement `Copy`
CopyClone
Écritureaucune : let m = n;explicite : x.clone()
Ce qui est copiéles octets de la valeur, sur la pilece que le type décide, tas compris
Coûtfixe et petitdépend du type et de la taille
Exemplesi32, bool, char, &TString, Vec<T>, HashMap<K, V>

Clone existe donc pour que la copie coûteuse soit visible dans le code. Un .clone() est un endroit où le programme peut allouer.

Un clone peut en cacher mille

Le coût d’un clone dépend de ce que la valeur contient. Avec le même compteur d’allocations :

fn main() {
    let noms: Vec<String> = (0..1000).map(|i| format!("utilisateur numéro {i}")).collect();

    let avant = allocs();
    let copie = noms.clone();
    let n_vec = allocs() - avant;

    let partage = Arc::new(noms);

    let avant = allocs();
    let autre = Arc::clone(&partage);
    let n_arc = allocs() - avant;

    let avant = allocs();
    let profond = (*partage).clone();
    let n_profond = allocs() - avant;

    println!("Vec<String>::clone  : {n_vec} allocations");
    println!("Arc::clone          : {n_arc} allocation");
    println!("(*partage).clone()  : {n_profond} allocations");
    println!("propriétaires de l'Arc : {}", Arc::strong_count(&partage));
    let _ = (copie.len(), autre.len(), profond.len());
}
Vec<String>::clone  : 1001 allocations
Arc::clone          : 0 allocation
(*partage).clone()  : 1001 allocations
propriétaires de l'Arc : 2

Trois écritures qui se ressemblent, trois coûts.

  • Cloner le Vec clone chaque élément : une allocation pour le tableau, plus une par String. Soit 1001 pour mille noms.
  • Cloner l’Arc n’alloue rien : il incrémente un compteur et rend un second pointeur vers les mêmes données. C’est pour ça que la convention est d’écrire Arc::clone(&partage) plutôt que partage.clone() : on voit à la lecture que ce clone-là est bon marché.
  • (*partage).clone() déréférence l’Arc et clone son contenu : retour à 1001. La différence avec la ligne précédente tient à une étoile.

Emprunter au lieu de cloner

Dans le premier exemple, afficher ne fait que lire son argument. La correction que la note du compilateur suggère est de le dire dans la signature :

fn afficher(s: &str) {
    println!("bonjour {s}");
}

fn main() {
    let nom = String::from("Ada");
    afficher(&nom);
    println!("{nom}");
}

Le choix du type de paramètre suit ce que la fonction fait de la valeur :

La fonction…ParamètreL’appelant écritAllocation
lit un texte&strf(&nom)aucune
lit une liste&[T]f(&v)aucune
lit une struct&Tf(&config)aucune
modifie sur place&mut Tf(&mut v)aucune
garde la valeur (la range, l’envoie à un thread)Tf(nom) ou f(nom.clone())seulement si l’appelant clone

La dernière ligne compte : quand la fonction a vraiment besoin de posséder, prendre T par valeur est le bon choix. L’appelant décide alors lui-même s’il donne sa valeur ou s’il en garde une copie.

Cow : ne copier que s’il le faut

Reste un cas que ni &str ni String ne couvrent bien : une fonction qui rend le plus souvent son entrée telle quelle, et parfois une version modifiée. Par exemple, remplacer les espaces par des tirets bas :

fn toujours(s: &str) -> String {
    s.replace(' ', "_")
}

Cette version alloue à chaque appel, même quand l’entrée ne contient aucun espace. Cow (clone on write) permet de rendre l’un ou l’autre :

use std::borrow::Cow;

fn si_besoin(s: &str) -> Cow<'_, str> {
    if s.contains(' ') {
        Cow::Owned(s.replace(' ', "_"))
    } else {
        Cow::Borrowed(s)
    }
}

fn variante(c: &Cow<'_, str>) -> &'static str {
    match c {
        Cow::Borrowed(_) => "Borrowed",
        Cow::Owned(_) => "Owned",
    }
}

fn main() {
    let lot = ["ada", "grace hopper", "linus"];

    let avant = allocs();
    for s in lot {
        let _propre = toujours(s);
    }
    let n_string = allocs() - avant;

    let mut n_cow = 0;
    for s in lot {
        let avant = allocs();
        let propre = si_besoin(s);
        let n = allocs() - avant;
        n_cow += n;
        println!("{propre:<12} {:<8} {n}", variante(&propre));
    }
    println!("String : {n_string} allocations");
    println!("Cow    : {n_cow} allocation");
}
ada          Borrowed 0
grace_hopper Owned    1
linus        Borrowed 0
String : 3 allocations
Cow    : 1 allocation

Cow n’a rien de magique : c’est un enum à deux variantes.

Cow<'a, str>
  ├─ Borrowed(&'a str)   un emprunt de l'entrée      0 allocation
  └─ Owned(String)       une nouvelle String         1 allocation

L’appelant n’a pas à savoir laquelle il a reçue. Un Cow<str> se lit comme un &str : propre.len(), println!("{propre}") et toutes les méthodes de str fonctionnent sur les deux variantes.

to_mut : la copie au moment d’écrire

Un Cow emprunté peut devenir possédé plus tard. to_mut() rend un accès en écriture, et fait la copie si elle n’a pas encore eu lieu :

fn main() {
    let mut c: Cow<'_, str> = Cow::Borrowed("ada");
    println!("avant  : {} ({c})", variante(&c));

    let avant = allocs();
    c.to_mut().make_ascii_uppercase();
    let n = allocs() - avant;
    println!("après  : {} ({c})", variante(&c));
    println!("to_mut : {n} allocation");

    let avant = allocs();
    c.to_mut().make_ascii_lowercase();
    let n = allocs() - avant;
    println!("encore : {} ({c}), {n} allocation", variante(&c));
}
avant  : Borrowed (ada)
après  : Owned (ADA)
to_mut : 1 allocation
encore : Owned (ada), 0 allocation

Le premier to_mut() trouve un Borrowed : il alloue, copie, et la valeur devient Owned. Le second trouve déjà un Owned et n’alloue rien. La copie a lieu une seule fois, à la première écriture.

Conséquence à connaître : appeler to_mut() sans vérifier s’il y a quelque chose à modifier annule tout le bénéfice, puisque chaque valeur empruntée est alors copiée. Le test doit venir avant.

clone sur une référence

Dernier piège : un .clone() qui ne clone pas ce qu’on croit.

struct Config {
    nom: String,
}

fn main() {
    let c = Config { nom: String::from("prod") };
    let r = &c;
    let d = r.clone();
    println!("{}", d.nom);
}
warning: call to `.clone()` on a reference in this situation does nothing
 --> noop.rs:8:14
  |
8 |     let d = r.clone();
  |              ^^^^^^^^
  |
  = note: the type `Config` does not implement `Clone`, so calling `clone` on `&Config` copies the reference, which does not do anything and can be removed
  = note: `#[warn(noop_method_call)]` on by default

Config n’est pas Clone. Mais les références partagées sont Copy, donc Clone : l’appel compile en clonant la référence. d est un second &Config, pas un Config. Le programme affiche bien prod, et aucune copie de la configuration n’existe.

Si le résultat doit être une valeur possédée, la même cause devient une erreur :

fn dupliquer(c: &Config) -> Config {
    c.clone()
}
error[E0308]: mismatched types
 --> reft.rs:6:5
  |
5 | fn dupliquer(c: &Config) -> Config {
  |                             ------ expected `Config` because of return type
6 |     c.clone()
  |     ^^^^^^^^^ expected `Config`, found `&Config`
  |
note: `Config` does not implement `Clone`, so `&Config` was cloned instead
 --> reft.rs:6:5
  |
6 |     c.clone()
  |     ^
help: consider annotating `Config` with `#[derive(Clone)]`
  |
1 + #[derive(Clone)]
2 | struct Config {
  |

Dans les deux cas, la correction est #[derive(Clone)] sur le type. Dans du code générique, la forme est la même : une fonction qui clone un &T doit demander T: Clone.

Ce que l’image cache

  • Cloner est parfois le bon geste. Quand la valeur doit vraiment exister deux fois (une copie pour un autre thread, une valeur rangée dans une struct qui vit plus longtemps), le clone est la réponse correcte. Sur une petite valeur, dans du code exécuté une fois au démarrage, son coût ne se mesure pas. Le problème est le clone écrit par réflexe sur un chemin exécuté des millions de fois.
  • to_owned(), to_string() et String::from sont de la même famille. Appliqués à un &str, tous allouent une String. Ils ne s’appellent pas clone, mais ils se comptent pareil.
  • Cow a un prix. Chaque accès teste la variante, la signature porte un lifetime, et le type se propage chez les appelants. Si la fonction modifie toujours son entrée, rendez une String ; si elle ne la modifie jamais, rendez un &str. Cow n’est justifié que pour le cas mixte, sur un chemin où l’allocation compte.
  • Cow ne se limite pas aux chaînes. Cow<[T]> fait la même chose entre &[T] et Vec<T>, et plus généralement Cow<B> entre &B et sa version possédée.
  • Rc se comporte comme Arc. Rc::clone incrémente un compteur sans rien copier. Rc::make_mut et Arc::make_mut appliquent la même idée que to_mut : ils ne clonent le contenu que s’il est partagé.
  • Une allocation n’est pas qu’une copie. Elle passe par l’allocateur, qui doit trouver un bloc libre et plus tard le reprendre. Sur un chemin chaud, c’est souvent ce travail, plus que la copie des octets, qui coûte.
  • Mesurer avant de corriger. Le compteur d’allocations de cet article tient en vingt lignes et dit où le programme alloue. C’est plus fiable que de relire le code à la recherche de .clone().

Pour aller plus loin

What the compiler suggests

The starting point is an error everyone runs into. A function takes a String, and the caller still wants to use it afterwards:

fn afficher(s: String) {
    println!("bonjour {s}");
}

fn main() {
    let nom = String::from("Ada");
    afficher(nom);
    println!("{nom}");
}
error[E0382]: borrow of moved value: `nom`
 --> deplace.rs:8:16
  |
6 |     let nom = String::from("Ada");
  |         --- move occurs because `nom` has type `String`, which does not implement the `Copy` trait
7 |     afficher(nom);
  |              --- value moved here
8 |     println!("{nom}");
  |                ^^^ value borrowed here after move
  |
note: consider changing this parameter type in function `afficher` to borrow instead if owning the value isn't necessary
 --> deplace.rs:1:16
  |
1 | fn afficher(s: String) {
  |    --------    ^^^^^^ this parameter takes ownership of the value
  |    |
  |    in this function
help: consider cloning the value if the performance cost is acceptable
  |
7 |     afficher(nom.clone());
  |                 ++++++++

The message contains two fixes, and they are not equivalent.

  • The note, first: change the parameter so that it borrows, if owning the value isn’t necessary. It asks you to modify the function.
  • The help, last: add .clone(), if the performance cost is acceptable. It is eight characters, at the call site, with the patch ready to copy.

The second is the easiest to apply, so it is the one most applied. The rest of this article measures what it costs.

What a clone costs

To see it, we replace the global allocator with one that counts its calls, then measure both spellings:

use std::alloc::{GlobalAlloc, Layout, System};
use std::sync::atomic::{AtomicUsize, Ordering};

struct Compteur;
static ALLOCS: AtomicUsize = AtomicUsize::new(0);

unsafe impl GlobalAlloc for Compteur {
    unsafe fn alloc(&self, l: Layout) -> *mut u8 {
        ALLOCS.fetch_add(1, Ordering::Relaxed);
        unsafe { System.alloc(l) }
    }
    unsafe fn dealloc(&self, p: *mut u8, l: Layout) {
        unsafe { System.dealloc(p, l) }
    }
}

#[global_allocator]
static A: Compteur = Compteur;

fn allocs() -> usize {
    ALLOCS.load(Ordering::Relaxed)
}

fn par_valeur(s: String) -> usize {
    s.len()
}

fn par_emprunt(s: &str) -> usize {
    s.len()
}

fn main() {
    let nom = String::from("Ada Lovelace");

    let avant = allocs();
    let n = par_valeur(nom.clone());
    let clone = allocs() - avant;

    let avant = allocs();
    let m = par_emprunt(&nom);
    let emprunt = allocs() - avant;

    let copie = nom.clone();
    let meme = nom.as_ptr() == copie.as_ptr();

    println!("clone   : {clone} allocation");
    println!("emprunt : {emprunt} allocation");
    println!("longueurs : {n} et {m}");
    println!("même tampon : {meme}");
}
clone   : 1 allocation
emprunt : 0 allocation
longueurs : 12 et 12
même tampon : false

(emprunt is the borrow, longueurs the lengths, même tampon “same buffer”.) Both functions return the same result. The first asked the system for memory, copied twelve bytes, then freed that memory when the call ended. The second received a pointer and a length.

The last line shows what a clone is: nom and copie have the same content, but not the same buffer.

       stack                      heap

nom    ┌ ptr ──────────────────▶ ┌──────────────┐
       │ len 12                  │ Ada Lovelace │
       └ cap 12                  └──────────────┘

copie  ┌ ptr ──────────────────▶ ┌──────────────┐   nom.clone():
       │ len 12                  │ Ada Lovelace │   one allocation,
       └ cap 12                  └──────────────┘   twelve bytes copied

s      ┌ ptr ──────────▶ (the buffer of nom)        &nom:
       └ len 12                                     nothing allocated

Copy and Clone: where the line is

Some types are copied without you writing anything, others are not. The rule depends on what the value owns.

#[derive(Debug, Clone, Copy)]
struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let n = 5;
    let m = n;
    println!("{n} {m}");

    let p = Point { x: 1, y: 2 };
    let q = p;
    println!("{p:?} {q:?}");

    let s = String::from("Ada");
    println!("String : {} octets sur la pile, {} dans le tas", std::mem::size_of_val(&s), s.len());
}
5 5
Point { x: 1, y: 2 } Point { x: 1, y: 2 }
String : 24 octets sur la pile, 3 dans le tas

An i32 or a Point lives entirely on the stack. Copying it means duplicating a few bytes: the language does it implicitly, and both variables stay usable. These types are Copy.

A String is 24 bytes on the stack (“sur la pile”) and 3 on the heap (“dans le tas”), but those 24 bytes are only the handle of a buffer. Duplicating them would give the same buffer two owners, hence two frees. The language refuses that implicit copy: it moves. And it also refuses to let you force it:

#[derive(Clone, Copy)]
struct Client {
    nom: String,
}
error[E0204]: the trait `Copy` cannot be implemented for this type
 --> copystr.rs:2:8
  |
1 | #[derive(Clone, Copy)]
  |                 ---- in this derive macro expansion
2 | struct Client {
  |        ^^^^^^
3 |     nom: String,
  |     ----------- this field does not implement `Copy`
CopyClone
Spellingnone: let m = n;explicit: x.clone()
What is copiedthe bytes of the value, on the stackwhatever the type decides, heap included
Costfixed and smalldepends on the type and the size
Examplesi32, bool, char, &TString, Vec<T>, HashMap<K, V>

So Clone exists to make the expensive copy visible in the code. A .clone() is a place where the program may allocate.

One clone can hide a thousand

The cost of a clone depends on what the value contains. With the same allocation counter:

fn main() {
    let noms: Vec<String> = (0..1000).map(|i| format!("utilisateur numéro {i}")).collect();

    let avant = allocs();
    let copie = noms.clone();
    let n_vec = allocs() - avant;

    let partage = Arc::new(noms);

    let avant = allocs();
    let autre = Arc::clone(&partage);
    let n_arc = allocs() - avant;

    let avant = allocs();
    let profond = (*partage).clone();
    let n_profond = allocs() - avant;

    println!("Vec<String>::clone  : {n_vec} allocations");
    println!("Arc::clone          : {n_arc} allocation");
    println!("(*partage).clone()  : {n_profond} allocations");
    println!("propriétaires de l'Arc : {}", Arc::strong_count(&partage));
    let _ = (copie.len(), autre.len(), profond.len());
}
Vec<String>::clone  : 1001 allocations
Arc::clone          : 0 allocation
(*partage).clone()  : 1001 allocations
propriétaires de l'Arc : 2

Three spellings that look alike, three costs.

  • Cloning the Vec clones each element: one allocation for the array, plus one per String. That is 1001 for a thousand names.
  • Cloning the Arc allocates nothing: it increments a counter and returns a second pointer to the same data (the last line counts two owners). That is why the convention is to write Arc::clone(&partage) rather than partage.clone(): you can see when reading that this clone is cheap.
  • (*partage).clone() dereferences the Arc and clones its content: back to 1001. The difference from the previous line is one asterisk.

Borrow instead of cloning

In the first example, afficher only reads its argument. The fix suggested by the compiler’s note is to say so in the signature:

fn afficher(s: &str) {
    println!("bonjour {s}");
}

fn main() {
    let nom = String::from("Ada");
    afficher(&nom);
    println!("{nom}");
}

The choice of parameter type follows what the function does with the value:

The function…ParameterThe caller writesAllocation
reads a text&strf(&nom)none
reads a list&[T]f(&v)none
reads a struct&Tf(&config)none
modifies in place&mut Tf(&mut v)none
keeps the value (stores it, sends it to a thread)Tf(nom) or f(nom.clone())only if the caller clones

The last row matters: when the function really needs to own, taking T by value is the right choice. The caller then decides whether to give its value away or keep a copy.

Cow: only copy when needed

One case remains that neither &str nor String covers well: a function that most often returns its input as is, and sometimes a modified version. For example, replacing spaces with underscores:

fn toujours(s: &str) -> String {
    s.replace(' ', "_")
}

This version allocates on every call, even when the input contains no space. Cow (clone on write) lets you return one or the other:

use std::borrow::Cow;

fn si_besoin(s: &str) -> Cow<'_, str> {
    if s.contains(' ') {
        Cow::Owned(s.replace(' ', "_"))
    } else {
        Cow::Borrowed(s)
    }
}

fn variante(c: &Cow<'_, str>) -> &'static str {
    match c {
        Cow::Borrowed(_) => "Borrowed",
        Cow::Owned(_) => "Owned",
    }
}

fn main() {
    let lot = ["ada", "grace hopper", "linus"];

    let avant = allocs();
    for s in lot {
        let _propre = toujours(s);
    }
    let n_string = allocs() - avant;

    let mut n_cow = 0;
    for s in lot {
        let avant = allocs();
        let propre = si_besoin(s);
        let n = allocs() - avant;
        n_cow += n;
        println!("{propre:<12} {:<8} {n}", variante(&propre));
    }
    println!("String : {n_string} allocations");
    println!("Cow    : {n_cow} allocation");
}
ada          Borrowed 0
grace_hopper Owned    1
linus        Borrowed 0
String : 3 allocations
Cow    : 1 allocation

There is nothing magic about Cow: it is an enum with two variants.

Cow<'a, str>
  ├─ Borrowed(&'a str)   a borrow of the input       0 allocations
  └─ Owned(String)       a new String                1 allocation

The caller does not need to know which one it received. A Cow<str> reads like a &str: propre.len(), println!("{propre}") and every method of str work on both variants.

to_mut: the copy at the moment of writing

A borrowed Cow can become owned later. to_mut() gives write access, and makes the copy if it has not happened yet:

fn main() {
    let mut c: Cow<'_, str> = Cow::Borrowed("ada");
    println!("avant  : {} ({c})", variante(&c));

    let avant = allocs();
    c.to_mut().make_ascii_uppercase();
    let n = allocs() - avant;
    println!("après  : {} ({c})", variante(&c));
    println!("to_mut : {n} allocation");

    let avant = allocs();
    c.to_mut().make_ascii_lowercase();
    let n = allocs() - avant;
    println!("encore : {} ({c}), {n} allocation", variante(&c));
}
avant  : Borrowed (ada)
après  : Owned (ADA)
to_mut : 1 allocation
encore : Owned (ada), 0 allocation

(avant is before, après after, encore again.) The first to_mut() finds a Borrowed: it allocates, copies, and the value becomes Owned. The second already finds an Owned and allocates nothing. The copy happens only once, at the first write.

A consequence worth knowing: calling to_mut() without checking whether there is anything to change cancels the whole benefit, since every borrowed value is then copied. The test has to come first.

clone on a reference

Last trap: a .clone() that does not clone what you think.

struct Config {
    nom: String,
}

fn main() {
    let c = Config { nom: String::from("prod") };
    let r = &c;
    let d = r.clone();
    println!("{}", d.nom);
}
warning: call to `.clone()` on a reference in this situation does nothing
 --> noop.rs:8:14
  |
8 |     let d = r.clone();
  |              ^^^^^^^^
  |
  = note: the type `Config` does not implement `Clone`, so calling `clone` on `&Config` copies the reference, which does not do anything and can be removed
  = note: `#[warn(noop_method_call)]` on by default

Config is not Clone. But shared references are Copy, hence Clone: the call compiles by cloning the reference. d is a second &Config, not a Config. The program does print prod, and no copy of the configuration exists.

If the result has to be an owned value, the same cause becomes an error:

fn dupliquer(c: &Config) -> Config {
    c.clone()
}
error[E0308]: mismatched types
 --> reft.rs:6:5
  |
5 | fn dupliquer(c: &Config) -> Config {
  |                             ------ expected `Config` because of return type
6 |     c.clone()
  |     ^^^^^^^^^ expected `Config`, found `&Config`
  |
note: `Config` does not implement `Clone`, so `&Config` was cloned instead
 --> reft.rs:6:5
  |
6 |     c.clone()
  |     ^
help: consider annotating `Config` with `#[derive(Clone)]`
  |
1 + #[derive(Clone)]
2 | struct Config {
  |

In both cases, the fix is #[derive(Clone)] on the type. In generic code, the shape is the same: a function that clones a &T must ask for T: Clone.

What the picture hides

  • Cloning is sometimes the right move. When the value really has to exist twice (a copy for another thread, a value stored in a struct that lives longer), the clone is the correct answer. On a small value, in code that runs once at startup, its cost cannot be measured. The problem is the clone written by reflex on a path that runs millions of times.
  • to_owned(), to_string() and String::from are the same family. Applied to a &str, they all allocate a String. They are not called clone, but they count the same.
  • Cow has a price. Each access tests the variant, the signature carries a lifetime, and the type spreads to the callers. If the function always modifies its input, return a String; if it never does, return a &str. Cow is only justified for the mixed case, on a path where the allocation matters.
  • Cow is not limited to strings. Cow<[T]> does the same between &[T] and Vec<T>, and more generally Cow<B> between &B and its owned version.
  • Rc behaves like Arc. Rc::clone increments a counter without copying anything. Rc::make_mut and Arc::make_mut apply the same idea as to_mut: they only clone the content if it is shared.
  • An allocation is more than a copy. It goes through the allocator, which has to find a free block and later take it back. On a hot path, that work, more than the copying of the bytes, is often what costs.
  • Measure before fixing. The allocation counter in this article is twenty lines long and tells you where the program allocates. That is more reliable than rereading the code looking for .clone().

Going further

Questions fréquentesFrequently asked questions

Que signifie « consider cloning the value if the performance cost is acceptable » ?What does "consider cloning the value if the performance cost is acceptable" mean?

C'est l'aide que rustc ajoute à l'erreur E0382, « borrow of moved value », quand une valeur est utilisée après avoir été déplacée. Ajouter .clone() fait compiler le programme : la fonction reçoit une copie et l'original reste utilisable. Mais la fin de la phrase compte. Cloner une String, un Vec ou une HashMap alloue de la mémoire et copie tout le contenu. Juste au-dessus, le même message propose souvent l'autre correction : changer le paramètre de la fonction pour qu'elle emprunte (&str, &[T], &T) si elle n'a pas besoin de posséder la valeur. Celle-là n'alloue rien.It is the help rustc adds to error E0382, "borrow of moved value", when a value is used after being moved. Adding .clone() makes the program compile: the function receives a copy and the original stays usable. But the end of the sentence matters. Cloning a String, a Vec or a HashMap allocates memory and copies the whole content. Just above, the same message often suggests the other fix: changing the function's parameter so that it borrows (&str, &[T], &T) if it does not need to own the value. That one allocates nothing.

Quelle différence entre Copy et Clone en Rust ?What is the difference between Copy and Clone in Rust?

Copy est une copie implicite et toujours bon marché : les octets de la valeur sont dupliqués sur la pile, sans appel de code et sans allocation. C'est le cas de i32, bool, char, des références partagées et des structs composées uniquement de champs Copy. Après let m = n, les deux variables restent utilisables. Clone est une copie explicite, écrite .clone(), dont le coût dépend du type : pour une String, une allocation et la copie du texte. Un type qui possède de la mémoire dans le tas ne peut pas être Copy : dériver Copy sur une struct qui contient une String donne l'erreur E0204.Copy is an implicit copy that is always cheap: the bytes of the value are duplicated on the stack, with no code called and no allocation. This is the case for i32, bool, char, shared references and structs made only of Copy fields. After let m = n, both variables stay usable. Clone is an explicit copy, written .clone(), whose cost depends on the type: for a String, one allocation and the copy of the text. A type that owns heap memory cannot be Copy: deriving Copy on a struct that contains a String gives error E0204.

Qu'est-ce que Cow en Rust et quand l'utiliser ?What is Cow in Rust and when should you use it?

Cow (clone on write) est un enum à deux variantes : Borrowed, qui contient une référence, et Owned, qui contient la valeur possédée. Cow<str> est donc soit un &str, soit une String. Il sert quand une fonction rend le plus souvent son entrée telle quelle, et parfois une version modifiée : elle rend Borrowed sans allouer dans le premier cas, Owned dans le second. Sur un lot de trois chaînes dont une seule doit changer, la version qui rend une String alloue trois fois, la version Cow une fois. Si la fonction modifie toujours, ou jamais, Cow n'apporte rien : rendez une String ou un &str.Cow (clone on write) is an enum with two variants: Borrowed, which holds a reference, and Owned, which holds the owned value. So Cow<str> is either a &str or a String. It is useful when a function most often returns its input as is, and sometimes a modified version: it returns Borrowed without allocating in the first case, Owned in the second. Over a batch of three strings where only one must change, the version returning a String allocates three times, the Cow version once. If the function always modifies, or never does, Cow brings nothing: return a String or a &str.

Arc::clone copie-t-il les données ?Does Arc::clone copy the data?

Non. Cloner un Arc (ou un Rc) incrémente un compteur de références et rend un nouveau pointeur vers les mêmes données : aucune allocation, quelle que soit la taille du contenu. Mesuré sur un Arc<Vec<String>> de mille éléments, Arc::clone fait 0 allocation, alors que cloner le Vec lui-même en fait 1001. L'écriture Arc::clone(&partage), plutôt que partage.clone(), est une convention qui rend ce coût visible à la lecture. Attention à (*partage).clone() : cette écriture déréférence l'Arc et clone le contenu en entier.No. Cloning an Arc (or an Rc) increments a reference count and returns a new pointer to the same data: no allocation, whatever the size of the content. Measured on an Arc<Vec<String>> of a thousand elements, Arc::clone makes 0 allocations, while cloning the Vec itself makes 1001. Writing Arc::clone(&partage), rather than partage.clone(), is a convention that makes this cost visible when reading. Watch out for (*partage).clone(): that spelling dereferences the Arc and clones the whole content.

Que veut dire « call to .clone() on a reference in this situation does nothing » ?What does "call to .clone() on a reference in this situation does nothing" mean?

Que le type visé n'implémente pas Clone, et que .clone() a donc copié la référence au lieu de la valeur. Les références partagées sont Copy : si r est un &Config et que Config n'est pas Clone, r.clone() rend un autre &Config, pas un Config. rustc le signale par le lint noop_method_call, actif par défaut. Si le résultat est attendu comme une valeur possédée, la même cause produit l'erreur E0308, « expected Config, found &Config ». La correction est d'ajouter #[derive(Clone)] au type, ou de retirer l'appel s'il ne servait à rien.That the target type does not implement Clone, so .clone() copied the reference instead of the value. Shared references are Copy: if r is a &Config and Config is not Clone, r.clone() returns another &Config, not a Config. rustc reports it through the noop_method_call lint, on by default. If the result is expected to be an owned value, the same cause produces error E0308, "expected Config, found &Config". The fix is to add #[derive(Clone)] to the type, or to remove the call if it served no purpose.

RustcloneCowPerformanceModèle mental

← Tous les articlesAll articles