Cow Str Clone On Write Borrowing

Return borrowed data untouched and allocate only when a rewrite is needed with Cow<str>, keeping one API for both zero-copy and owned results.

RustData Integrity

Code

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

fn normalize(input: &str) -> Cow<'_, str> {
    if input.chars().any(|c| c.is_uppercase()) {
        // 需要改写时才分配:to_lowercase 产生新的 String
        Cow::Owned(input.to_lowercase())
    } else {
        // 已合规:零拷贝借用原切片
        Cow::Borrowed(input)
    }
}

fn main() {
    for input in ["already-normalized", "Mixed-CASE-Id"] {
        match normalize(input) {
            Cow::Borrowed(b) => println!("borrowed, zero alloc: {b}"),
            Cow::Owned(o) => println!("owned after rewrite: {o}"),
        }
    }
}

How it works

Cow Str Clone On Write Borrowing keeps everything in the functions normalize and main.

Repetition is confined to for input in ["already-normalized", "Mixed-CASE-Id"] — the rest of the file is straight-line. Each possible shape of the input gets its own match arm, and the compiler checks the set is complete.

Applying it

The main signature reads fn normalize(input: &str) -> Cow<'_, str>

The demo output is labeled (borrowed, zero alloc:, owned after rewrite:), so every printed line maps back to its originating operation.

Treat main as the orchestrator calling normalize in a fixed order.

Statements that matter

fn normalize(input: &str) -> Cow<'_, str> {
if input.chars().any(|c| c.is_uppercase()) {
// 需要改写时才分配:to_lowercase 产生新的 String
Cow::Owned(input.to_lowercase())
} else {
// 已合规:零拷贝借用原切片
Cow::Borrowed(input)
}
}
match normalize(input) {
Cow::Borrowed(b) => println!("borrowed, zero alloc: {b}"),
Cow::Owned(o) => println!("owned after rewrite: {o}"),
}

Interactive Tools for This Topic

FAQ

What does Cow Str Clone On Write Borrowing print when run?
Run it as a complete program — the output lines carry labels such as `borrowed, zero alloc:`, `owned after rewrite:`.