In Rust, what does `Cow::to_mut` do on a `Cow::Borrowed` versus a `Cow::Owned`, and how does it differ from `into_owned`?
answer
- mutable access to the owned form
- clone happens at most once
- the variant switches in place
- consume versus borrow mutably
basics
~20 sCow::to_mut takes &mut self and returns a mutable reference to the owned value: on Borrowed it clones the data once and switches the Cow to Owned, on Owned it clones nothing. into_owned consumes the Cow and returns the owned value, cloning only if Borrowed.
solid answer
~40 s`Cow` implements `Deref` but not `DerefMut`, so writing through it (`c[0] = 5`, `c.push_str(..)`) does not compile; `to_mut` is the way in. Its signature is `fn to_mut(&mut self) -> &mut <B as ToOwned>::Owned`, so for `Cow<'_, str>` you get `&mut String` and for `Cow<'_, [T]>` a `&mut Vec<T>`. On `Cow::Borrowed(b)` it runs `*self = Owned(b.to_owned())`, a single clone, and returns a reference into the new owned value; on `Cow::Owned` it just returns a reference, so later calls never clone again. The borrowed original is never touched. `into_owned(self)` is the other exit: it consumes the `Cow` and returns the owned value, moving it out of `Owned` for free or cloning a `Borrowed`. Use `to_mut` to edit and keep the `Cow`; use `into_owned` when you need the value itself, to store or return.
code
rust · 18 linesuse std::borrow::Cow;
fn main() {
let words = ["alpha", "beta"];
let mut cow: Cow<'_, [&str]> = Cow::Borrowed(&words);
// First to_mut: Borrowed -> clones the slice into a Vec, switches to Owned
cow.to_mut().push("gamma");
println!("{}", matches!(cow, Cow::Owned(_)));
// Second to_mut: already Owned, returns &mut Vec with no new clone
cow.to_mut().push("delta");
println!("{cow:?} / original: {words:?}");
// into_owned consumes the Cow; for Owned it moves the Vec out, no copy
let v: Vec<&str> = cow.into_owned();
println!("{}", v.len());
}go deeper
Recall that you cannot write through a Cow directly and that to_mut gives you a mutable String or Vec to edit.
Walk through to_mut: one clone on Borrowed, the variant switch, no clone on Owned. Contrast it with into_owned, which consumes the Cow.
Place to_mut inside the branch that writes so clean inputs never clone, and know that cloning an Owned Cow is a full copy rather than a shared buffer.
Use to_mut versus into_owned as a review signal: one keeps the borrowed-or-owned choice open for callers, the other commits to ownership at that point.
## Why `Cow` needs `to_mut` `std::borrow::Cow<'a, B>` is an enum of `Borrowed(&'a B)` and `Owned(<B as ToOwned>::Owned)`. It implements `Deref<Target = B>`, so **reading** is transparent. It deliberately does **not** implement `DerefMut`: the `Borrowed` case holds a shared reference, and there is no way to hand out `&mut B` through one. rustc enforces this: - `c[0] = 5;` on a `Cow<'_, [i32]>` fails with E0594, "cannot assign to data in dereference of `Cow<'_, [i32]>`", and its help line says `DerefMut` is required but not implemented. - `c.push_str("x")` on a `Cow<'_, str>` fails with E0599, because the deref target `str` has no `push_str`. **Mutation goes through `to_mut`**, which is where the "clone-on-write" in the type's name happens. ## `to_mut` step by step The signature is `pub fn to_mut(&mut self) -> &mut <B as ToOwned>::Owned`. It returns a mutable reference to the **owned** type, not to `B`: `&mut String` for `Cow<'_, str>`, `&mut Vec<T>` for `Cow<'_, [T]>`. The implementation: 1. Matches on `*self`. 2. If it is `Borrowed(borrowed)`, it calls `borrowed.to_owned()`, which clones the data, and **overwrites `self`** with `Owned(...)`. The `Cow` has switched variants in place. 3. It then returns `&mut` to the value inside `Owned`. 4. If it was already `Owned(ref mut owned)`, it returns `owned` straight away. No clone. The consequences: - **At most one clone per `Cow`**, on the first call. Ten later calls cost nothing extra. - **The original is never modified.** A `Borrowed` `Cow` over a caller's slice copies it; the caller's data stays exactly as it was. - **Call it only where you write.** std's own documentation example walks a `Cow<'_, [i32]>` and calls `input.to_mut()[i] = -v` only inside the `if v < 0` branch, so an all-positive input is never cloned. Calling `to_mut` at the top of the function would clone even when nothing changes. ## `into_owned` `pub fn into_owned(self) -> <B as ToOwned>::Owned` takes the `Cow` **by value**: - On `Owned(owned)` it returns `owned`. The documentation states the data is moved out without being cloned. - On `Borrowed(borrowed)` it returns `borrowed.to_owned()`, a fresh clone. After `into_owned` the `Cow` is gone; you hold a plain `String` or `Vec<T>` with no lifetime attached, which is what you need to store the value in a long-lived struct, return it from a function that owns nothing, or send it to another thread. ## A trace through the example The code example starts with `let words = ["alpha", "beta"]` and a `Cow<'_, [&str]>` borrowing it: 1. The first `cow.to_mut()` finds `Borrowed`, calls `to_owned()` on the slice, which runs `to_vec()` and allocates a `Vec<&str>` holding copies of the two references, stores `Owned(vec)` in `cow`, and returns `&mut Vec<&str>`. `push("gamma")` then grows that `Vec`. 2. `matches!(cow, Cow::Owned(_))` prints `true`: the variant switched in place. 3. The second `cow.to_mut()` finds `Owned` and returns the same `Vec`; `push("delta")` appends with no further clone. 4. Printing shows four elements in the `Cow` and the untouched two-element `words` array. 5. `cow.into_owned()` moves the `Vec` out with no copy, and `v.len()` is 4. Note that cloning a slice of `&str` copies the references, not the text they point to: `to_owned()` clones each element with its own `Clone` impl, and `Clone` for a reference is a pointer copy. ## Side by side | | `to_mut` | `into_owned` | |---|---|---| | Receiver | `&mut self` | `self` (consumes) | | Returns | `&mut <B as ToOwned>::Owned` | `<B as ToOwned>::Owned` | | On `Borrowed` | clones once, becomes `Owned` | clones | | On `Owned` | no clone | moves out, no clone | | `Cow` usable afterwards | yes, now `Owned` | no | ## Related behaviour worth knowing - **`Clone` on a `Cow`** copies the reference for `Borrowed` but makes a **full copy** of the owned data for `Owned`: its implementation calls `to_owned()` on the borrowed view. There is no sharing. - **`+=` on `Cow<'a, str>`** is implemented with `to_mut`. Appending to an empty `Cow` simply replaces it with `Borrowed(rhs)`, appending an empty string to a non-empty one changes nothing, and otherwise a `Borrowed` left side is copied into a `String` with capacity for both before the right side is pushed. - **Shared ownership with clone-on-write** is a different tool: reference-counted pointers have their own `make_mut`, covered with `Rc`. `Cow` has a single owner and no counter. ## Common mistakes - Expecting `*cow = ...` or index assignment to trigger the clone automatically. - Calling `to_mut` "just in case" before knowing whether a write will happen. - Using `into_owned` to edit and then rebuilding a `Cow`, when `to_mut` would have kept it in place. - Believing `to_mut` writes through to the borrowed source.
- What goes wrong if a loop calls `to_mut` on every iteration but only sometimes writes?Nothing is cloned twice, because after the first call the `Cow` is `Owned`. The waste is the first call: if it runs before you know a write is needed, the borrowed data is cloned even when the loop changes nothing. Call `to_mut` only inside the branch that writes, as std's `abs_all` example does for negative numbers.
- Does cloning a `Cow::Owned` share its buffer?No. `Clone` for `Cow` copies the reference in the `Borrowed` case, but for `Owned` it calls `to_owned()` on the borrowed view and builds a new `String` or `Vec`, a full copy. For one buffer shared by several owners with a copy only on write, a reference-counted pointer's `make_mut` is the tool, covered with `Rc`.
- Why does `to_mut` return `&mut String` rather than `&mut str` for a `Cow<'_, str>`?Because it returns `&mut <B as ToOwned>::Owned`, and `str`'s owned type is `String`. Getting the owned form is the point: a `&mut str` could only edit bytes in place, while `&mut String` can push, insert, truncate and reallocate, which is what most edits need.
Reading a library book costs nothing; the first time you want to write in the margins you photocopy it, and every later note goes on your copy while the library's book stays clean.
- to_mut clones the data every time it is called.
- to_mut writes the change back into the original borrowed data.
- into_owned on a Cow::Owned clones the String.
- Index assignment on a Cow clones the data automatically.
- Cloning a Cow::Owned is a cheap pointer copy, like Rc::clone.