本文簡要介紹rust語言中 Enum alloc::borrow::Cow
的用法。
用法
pub enum Cow<'a, B: ?Sized + 'a> where B: ToOwned, {
Borrowed(&'a B),
Owned(<B as ToOwned>::Owned),
}
clone-on-write 智能指針。
類型 Cow
是一個提供 clone-on-write 函數的智能指針:它可以封裝並提供對借用數據的不可變訪問,並在需要突變或所有權時延遲克隆數據。該類型旨在通過 Borrow
特征處理一般借用數據。
Cow
實現了 Deref
,這意味著您可以直接在其包含的數據上調用非變異方法。如果需要突變,to_mut
將獲得對擁有值的可變引用,並在必要時進行克隆。
如果您需要引用計數指針,請注意 Rc::make_mut
和 Arc::make_mut
也可以提供 clone-on-write 函數。
例子
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);
另一個顯示如何將 Cow
保留在結構中的示例:
use std::borrow::Cow;
struct Items<'a, X: 'a> 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 check it out.
match clone_on_write {
Items { values: Cow::Owned(_) } => println!("clone_on_write contains owned data"),
_ => panic!("expect owned data"),
}
變體
Borrowed(&'a B)
元組字段
0: &'a B
借來的資料。
Owned(<B as ToOwned>::Owned)
擁有的數據。
相關用法
- Rust Cow.is_owned用法及代碼示例
- Rust Cow.into_owned用法及代碼示例
- Rust Cow.is_borrowed用法及代碼示例
- Rust Cow.to_mut用法及代碼示例
- Rust Condvar.notify_all用法及代碼示例
- Rust Command.args用法及代碼示例
- Rust Condvar.wait用法及代碼示例
- Rust Condvar.wait_timeout用法及代碼示例
- Rust Condvar.wait_timeout_while用法及代碼示例
- Rust Command.env用法及代碼示例
- Rust Command.env_remove用法及代碼示例
- Rust Command.get_args用法及代碼示例
- Rust Command.stdout用法及代碼示例
- Rust Command.stdin用法及代碼示例
- Rust Components用法及代碼示例
- Rust Component.as_os_str用法及代碼示例
- Rust ControlFlow用法及代碼示例
- Rust Command.current_dir用法及代碼示例
- Rust Command.output用法及代碼示例
- Rust ControlFlow.break_value用法及代碼示例
- Rust Command.status用法及代碼示例
- Rust Condvar.wait_while用法及代碼示例
- Rust Command.envs用法及代碼示例
- Rust Command用法及代碼示例
- Rust Command.get_program用法及代碼示例
注:本文由純淨天空篩選整理自rust-lang.org大神的英文原創作品 Enum alloc::borrow::Cow。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。