Why does `Cow<'_, [Token]>` fail with E0277 when `Token` is not `Clone`, and why do Rust APIs write `Cow<str>` rather than `Cow<String>`?
answer
- a bound on the enum itself
- B is the borrowed form
- ToOwned pairs str with String
- slices need Clone elements
basics
~20 sCow<'a, B> requires B: ToOwned, and std implements ToOwned for [T] only when T: Clone, so naming Cow<[Token]> fails with E0277 even if nothing is ever cloned. B is the borrowed form: str, whose owned type is String.
solid answer
~50 sThe definition is `enum Cow<'a, B: ?Sized + 'a> where B: ToOwned { Borrowed(&'a B), Owned(<B as ToOwned>::Owned) }`. Because the bound sits on the type itself, rustc checks it wherever `Cow<'_, [Token]>` is named, not only when `to_mut` runs, and std's only impl for slices is `impl<T: Clone> ToOwned for [T]` with `Owned = Vec<T>`. So without `Token: Clone` you get E0277, "the trait bound `[Token]: ToOwned` is not satisfied"; the fix is to derive `Clone` or not use `Cow`. The parameter `B` is the **borrowed** form, and `?Sized` lets it be `str` or `[T]`: `Cow<str>` borrows any `&str` (a literal, a substring) and owns a `String`. `Cow<String>` does compile, through the blanket `impl<T: Clone> ToOwned for T`, but its borrowed case is a `&String`, which cannot point at a literal or a slice, and `"x".into()` into it fails with E0277.
code
rust · 9 linesuse std::borrow::Cow;
struct Token(u32); // no Clone
fn main() {
let ts = [Token(1), Token(2)];
let c: Cow<'_, [Token]> = Cow::Borrowed(&ts);
println!("{}", c.len());
}go deeper
Recall that Cow takes the borrowed type as its parameter: Cow<str> owns a String, and Cow<[T]> owns a Vec<T>.
Explain the B: ToOwned bound on the enum and how the Owned type is derived from it, including why ?Sized is there.
Diagnose the E0277 from the bound on the type, not from a method call. Explain why Cow<String> compiles yet is the wrong design, and give the fix.
Insist that types are parameterised by the borrowed form, Cow<str>, Cow<[T]> and Cow<Path>, so APIs accept literals and subslices without extra copies.
## The definition and its bound `std::borrow::Cow` is declared in `alloc/src/borrow.rs` as: ```rust pub enum Cow<'a, B: ?Sized + 'a> where B: ToOwned, { Borrowed(&'a B), Owned(<B as ToOwned>::Owned), } ``` Three facts follow from this one declaration: - **`B` is the borrowed form**, the type behind the reference in `Borrowed(&'a B)`. - **The owned form is not a second parameter.** It is computed as the associated type `<B as ToOwned>::Owned`, so `B` alone decides what `Owned` holds. - **`B: ToOwned` is a bound on the type**, not on a method. Every place that names `Cow<'_, X>` must prove `X: ToOwned`, even code that only ever builds `Cow::Borrowed` and never clones. `?Sized` relaxes the implicit `Sized` bound that every type parameter carries, which is what lets `B` be a dynamically sized type such as `str` or `[T]`. `&'a str` and `&'a [T]` are fat pointers, so the `Borrowed` variant itself stays sized. ## Where the bound bites: E0277 Take a slice of a type that is not `Clone`: ```rust struct Token(u32); // no Clone let c: Cow<'_, [Token]> = Cow::Borrowed(&ts); ``` rustc 1.99.1 rejects it with `error[E0277]: the trait bound `[Token]: ToOwned` is not satisfied`, adds a help line pointing at `impl<T: Clone> ToOwned for [T]` with "unsatisfied requirement introduced here: `Token: Clone`", and notes the requirement comes from the `B: ToOwned` bound on `Cow`. The reasoning chain is: 1. `Cow<'_, [Token]>` needs `[Token]: ToOwned`. 2. std's only impl for slices is `impl<T: Clone> ToOwned for [T]`, with `type Owned = Vec<T>`, implemented with `to_vec()`. 3. `Token` is not `Clone`, so the impl does not apply. Fixes, in order of preference: - **Derive `Clone`** on the element type if copying it is meaningful. - **Drop `Cow`** and take `&[Token]` or `Vec<Token>` directly if the clone-on-write path was never needed. ## The `ToOwned` pairs in std | Borrowed `B` | `<B as ToOwned>::Owned` | Condition | |---|---|---| | `str` | `String` | none | | `[T]` | `Vec<T>` | `T: Clone` | | `Path` | `PathBuf` | none | | `OsStr` | `OsString` | none | | `CStr` | `CString` | none | | any `T` | `T` | `T: Clone` (blanket impl) | The blanket `impl<T> ToOwned for T where T: Clone` is what makes `Cow<'a, Config>` legal for a `Config: Clone` struct: `Borrowed(&'a Config)` or `Owned(Config)`. ## Reading the diagnostic rustc 1.99.1 prints **three** E0277 errors for the one-line example: one for the type annotation `Cow<'_, [Token]>`, one for the `Cow::Borrowed` constructor and one for its argument `&ts`, because each of them involves the type and must satisfy the bound. Each carries the same three parts, and reading them in order explains the failure without guesswork: 1. the **unmet bound**: `[Token]: ToOwned`; 2. the **candidate impl** rustc considered, `impl<T: Clone> ToOwned for [T]`, with the requirement it could not meet, `Token: Clone`; 3. the **origin** of the bound: the `B: ToOwned` line in the declaration of `Cow`. The lesson for code review is that the error appears at the type, before any method is called. A generic struct holding `Cow<'a, [T]>` must therefore carry `T: Clone` (or the equivalent `[T]: ToOwned`) in its own bounds; std's documentation shows exactly that with a `where [X]: ToOwned<Owned = Vec<X>>` clause on a struct with a `Cow<'a, [X]>` field. ## Why `Cow<str>`, not `Cow<String>` `Cow<'a, String>` compiles: `String: Clone`, so the blanket impl gives `Owned = String`. But it is the wrong shape: - **The borrowed case is `&'a String`**, a reference to someone's `String` header. It cannot borrow a string literal, a substring from `split` or `trim`, or text inside a larger buffer; all of those are `&str`. - **The `From` impls are not there.** std provides `From<&'a str>`, `From<&'a String>` and `From<String>` for `Cow<'a, str>`; for `Cow<'_, String>`, `"literal".into()` fails with E0277, "the trait bound `Cow<'_, String>: From<&str>` is not satisfied". - **Reading costs an extra hop**: deref goes `Cow` to `&String` to the bytes, where `Cow<str>` holds the fat pointer to the bytes directly. The same reasoning gives `Cow<'a, [T]>` over `Cow<'a, Vec<T>>` and `Cow<'a, Path>` over `Cow<'a, PathBuf>`: always parameterise by the borrowed form. ## Where the detailed contract lives What `ToOwned` and `Borrow` promise in general (that the owned value's `Borrow<B>` view must agree with the original, and how they differ from `Clone` and `AsRef`) belongs with the conversion traits. For `Cow`, the working rule is shorter: pick the borrowed type, check that it implements `ToOwned`, and the owned type comes for free.
- Can you write `Cow<'a, Settings>` for your own struct?Yes, if `Settings: Clone`. The blanket `impl<T: Clone> ToOwned for T` gives `Owned = Settings`, so the variants are `Borrowed(&'a Settings)` and `Owned(Settings)`. That fits defaults borrowed from a shared value and cloned only when a caller overrides a field through `to_mut`. A custom borrowed/owned pair, like `str` and `String`, needs its own `ToOwned` impl.
- What would break if `Cow` dropped the `?Sized` on `B`?Type parameters are implicitly `Sized`, and `str` and `[T]` are dynamically sized, so `Cow<str>` and `Cow<[T]>` would no longer be valid types. Only sized types such as `String` or `Vec<T>` could be named, which brings back the `Cow<String>` problems: no borrowing of literals or subslices.
- Cow<[T]> needs T: Clone only when to_mut is actually called.
- Cow<String> is the idiomatic borrowed-or-owned string type.
- Cow requires B: Clone, so str cannot be used with it.
- The E0277 is fixed by adding an explicit lifetime to the Cow.
- ToOwned for [T] produces a Box<[T]>.