当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Rust Cow用法及代码示例


本文简要介绍rust语言中 Enum std::borrow::Cow 的用法。

用法

pub enum Cow<'a, B> where    B: 'a + ToOwned + ?Sized,  {
    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)

元组字段

0: <B as ToOwned>::Owned

拥有的数据。

相关用法


注:本文由纯净天空筛选整理自rust-lang.org大神的英文原创作品 Enum std::borrow::Cow。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。