The type Cow is a smart pointer providing clone-on-write functionality: it
can enclose and provide immutable access to borrowed data, and clone the
data lazily when mutation or ownership is required. The type is designed to
work with general borrowed data via the Borrow trait.
Cow implements Deref, which means that you can call
non-mutating methods directly on the data it encloses. If mutation
is desired, to_mut will obtain a mutable reference to an owned
value, cloning if necessary.
If you need reference-counting pointers, note that
Rc::make_mut and
Arc::make_mut can provide clone-on-write
functionality as well.
use std::borrow::Cow;
fn abs_all(input: &mut Cow<'_, [i32]>) {
for i in 0..input.len() {
let v = input[i];
if v < 0 {
// Clones into a vector if not already owned.
input.to_mut()[i] = -v;
}
}
}
// No clone occurs because `input` doesn't need to be mutated.
let slice = [0, 1, 2];
let mut input = Cow::from(&slice[..]);
abs_all(&mut input);
// Clone occurs because `input` needs to be mutated.
let slice = [-1, 0, 1];
let mut input = Cow::from(&slice[..]);
abs_all(&mut input);
// No clone occurs because `input` is already owned.
let mut input = Cow::from(vec![-1, 0, 1]);
abs_all(&mut input);
Another example showing how to keep Cow in a struct:
use std::borrow::Cow;
struct Items<'a, X> where [X]: ToOwned<Owned = Vec<X>> {
values: Cow<'a, [X]>,
}
impl<'a, X: Clone + 'a> Items<'a, X> where [X]: ToOwned<Owned = Vec<X>> {
fn new(v: Cow<'a, [X]>) -> Self {
Items { values: v }
}
}
// Creates a container from borrowed values of a slice
let readonly = [1, 2];
let borrowed = Items::new((&readonly[..]).into());
match borrowed {
Items { values: Cow::Borrowed(b) } => println!("borrowed {b:?}"),
_ => panic!("expect borrowed value"),
}
let mut clone_on_write = borrowed;
// Mutates the data from slice into owned vec and pushes a new value on top
clone_on_write.values.to_mut().push(3);
println!("clone_on_write = {:?}", clone_on_write.values);
// The data was mutated. Let's check it out.
match clone_on_write {
Items { values: Cow::Owned(_) } => println!("clone_on_write contains owned data"),
_ => panic!("expect owned data"),
}
#![feature(cow_is_borrowed)]
use std::borrow::Cow;
let cow = Cow::Borrowed("moo");
assert!(cow.is_borrowed());
let bull: Cow<'_, str> = Cow::Owned("...moo?".to_string());
assert!(!bull.is_borrowed());
#![feature(cow_is_borrowed)]
use std::borrow::Cow;
let cow: Cow<'_, str> = Cow::Owned("moo".to_string());
assert!(cow.is_owned());
let bull = Cow::Borrowed("...moo?");
assert!(!bull.is_owned());
use std::borrow::Cow;
let mut cow = Cow::Borrowed("foo");
cow.to_mut().make_ascii_uppercase();
assert_eq!(
cow,
Cow::Owned(String::from("FOO")) as Cow<'_, str>
);
When cow is the Cow::Borrowed variant, this
conversion allocates on the heap and copies the
underlying slice. Otherwise, it will try to reuse the owned
Vec’s allocation.
When cow is the Cow::Borrowed variant, this
conversion allocates on the heap and copies the
underlying str. Otherwise, it will try to reuse the owned
String’s allocation.
If s already owns a Vec<T>, it will be returned directly.
If s is borrowing a slice, a new Vec<T> will be allocated and
filled by cloning s’s items into it.
// If the string is not owned...
let cow: Cow<'_, str> = Cow::Borrowed("eggplant");
// It will allocate on the heap and copy the string.
let owned: String = String::from(cow);
assert_eq!(&owned[..], "eggplant");
use std::error::Error;
use std::mem;
use std::borrow::Cow;
let a_cow_str_error = Cow::from("a str error");
let a_boxed_error = Box::<dyn Error>::from(a_cow_str_error);
assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))