Cow<'a, T> — clone on write — is an enum with two variants:
enum Cow<'a, T> {
Borrowed(&'a T),
Owned(T::Owned),
}
It lets a function return borrowed data on the common path and owned data only when it actually had to change something:
fn sanitize(input: &str) -> Cow<'_, str> {
if input.contains(' ') {
Cow::Owned(input.replace(' ', "_")) // allocated: we changed it
} else {
Cow::Borrowed(input) // free: nothing to do
}
}
