Cow To Mut Mutates Only When Owned

to_mut converts the borrowed Cow into an owned buffer only when a write happens, and into_owned returns a String either way.

RustData Integrity

Code

rustsnippet
19 lines
use std::borrow::Cow;

fn main() {
    let mut name: Cow<'_, str> = Cow::Borrowed("server");

    // to_mut converts to owned only when we actually write
    if !name.ends_with("-01") {
        name.to_mut().push_str("-01");
    }
    println!("name: {name}");

    // now owned: further writes mutate the buffer in place, no re-clone
    name.to_mut().push_str("-beta");
    println!("name: {name}");

    // into_owned hands back a String whether it borrowed or not
    let final_name: String = name.into_owned();
    println!("final: {final_name}");
}

How the pieces connect — Cow To Mut Mutates Only When Owned

The snippet is organized around the function main.

What to watch for

  • Runs on the standard library alone; nothing to install.

Using it

The type that anchors the demo: fn main()

The run prints name:, final: — each prefix names the step that produced it.

Key statements

let mut name: Cow<'_, str> = Cow::Borrowed("server");
let final_name: String = name.into_owned();
name.to_mut().push_str("-beta");

Interactive Tools for This Topic

FAQ

What does Cow To Mut Mutates Only When Owned print when run?
Execute the whole file; each printed line is prefixed with a label like `name:`, `final:`.