我可以拥有可以从切片和拥有缓冲区构建的结构吗?

时间:2017-06-21 13:06:50

标签: rust

我会尽量保持清醒。我想我有:

struct Foo<'a> {
    buffer: &'a [u8],
}

impl<'a> Foo<'a> {
    fn create_builder() -> FooBuilder {
        FooBuilder::new()
    }

    fn from_slice(slice: &[u8]) -> Foo {
        Foo { buffer: slice }
    }
}

struct FooBuilder {
    in_progress_buffer: Vec<u8>,
}

impl FooBuilder {
    fn new() -> FooBuilder {
        FooBuilder { in_progress_buffer: Vec::new() }
    }

    fn push(&mut self, item: u8) {
        self.in_progress_buffer.push(item);
    }

    fn build_foo(self) -> Foo {
        Foo { buffer: self.in_progress_buffer }
    }
}

fn main() {
    // Option1: Gradually construct Foo from FooBuilder
    let mut foo_builder = FooBuilder::new();
    foo_builder.push(7);
    let foo = foo_builder.build_foo();

    // Option2: Construct Foo from a slice
    let v = vec![7];
    let foo2 = Foo::from_slice(&v);
}

这会产生编译错误:

error[E0106]: missing lifetime specifier
  --> src/main.rs:28:27
   |
28 |     fn build_foo(self) -> Foo {
   |                           ^^^ expected lifetime parameter
   |
   = help: this function's return type contains a borrowed value, but there is no value for it to be borrowed from
   = help: consider giving it a 'static lifetime

这种模式可能吗?如何修复编译错误? 我不确定要生成什么生命周期说明符,因为在FooBuilder版本中,FooBuilder拥有缓冲区,我不想强​​迫Foo用户保留{{1在整个持续时间范围内使用FooBuilder

1 个答案:

答案 0 :(得分:2)

您可以使用std::borrow::Cow;作为docs州:

  

它可以包含并提供对借来数据的不可变访问,并在需要变异或所有权时懒惰地克隆数据

use std::borrow::Cow;

struct Foo<'a> {
    buffer: Cow<'a, [u8]>,
}

impl<'a> Foo<'a> {
    fn create_builder() -> FooBuilder {
        FooBuilder::new()
    }

    fn from_slice(slice: &[u8]) -> Foo {
        Foo { buffer: slice.into() } // note .into()
    }
}

struct FooBuilder {
    in_progress_buffer: Vec<u8>,
}

impl<'a> FooBuilder {
    fn new() -> FooBuilder {
        FooBuilder { in_progress_buffer: Vec::new() }
    }

    fn push(&mut self, item: u8) {
        self.in_progress_buffer.push(item);
    }

    fn build_foo(self) -> Foo<'a> {
            Foo { buffer: self.in_progress_buffer.into() } // note .into()
    }
}

此外,您需要将foo_builder变为可变,以便能够对其执行push