我有以下问题:我有一个数据 struct ,它是从缓冲区解析的,并且包含一些对这个缓冲区的引用,所以解析函数看起来像
fn parse_bar<'a>(buf: &'a [u8]) -> Bar<'a>
到目前为止,一切顺利.然而,为了避免某些生命周期问题,我希望将数据 struct 和底层缓冲区放入 struct 中,如下所示:
struct BarWithBuf<'a> {bar: Bar<'a>, buf: Box<[u8]>}
// not even sure if these lifetime annotations here make sense,
// but it won't compile unless I add some lifetime to Bar
然而,现在我不知道如何构造一个BarWithBuf
的值.
fn make_bar_with_buf<'a>(buf: Box<[u8]>) -> BarWithBuf<'a> {
let my_bar = parse_bar(&*buf);
BarWithBuf {buf: buf, bar: my_bar}
}
不起作用,因为在BarWithBuf值的构造中移动了buf
,但我们borrow 它进行解析.
我觉得应该可以按照
fn make_bar_with_buf<'a>(buf: Box<[u8]>) -> BarWithBuf<'a> {
let mut bwb = BarWithBuf {buf: buf};
bwb.bar = parse_bar(&*bwb.buf);
bwb
}
为了避免在解析Bar
之后移动缓冲区,但我不能这样做,因为整个BarWithBuf
struct 必须一次性初始化.