我有以下问题:我有一个从缓冲区解析的数据结构,并包含对这个缓冲区的一些引用,所以解析函数看起来像
fn parse_bar<'a>(buf: &'a [u8]) -> Bar<'a>
Run Code Online (Sandbox Code Playgroud)
到现在为止还挺好。但是,为了避免某些生命周期问题,我想将数据结构和底层缓冲区放入一个结构中,如下所示:
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
Run Code Online (Sandbox Code Playgroud)
但是,现在我不知道如何实际构造一个BarWithBuf值。
fn make_bar_with_buf<'a>(buf: Box<[u8]>) -> BarWithBuf<'a> {
let my_bar = parse_bar(&*buf);
BarWithBuf {buf: buf, bar: my_bar}
}
Run Code Online (Sandbox Code Playgroud)
不起作用,因为buf在 BarWithBuf 值的构造中移动了,但我们借用了它进行解析。
我觉得应该可以做一些类似的事情
fn make_bar_with_buf<'a>(buf: Box<[u8]>) -> BarWithBuf<'a> {
let mut bwb = BarWithBuf {buf: buf};
bwb.bar = parse_bar(&*bwb.buf);
bwb
} …Run Code Online (Sandbox Code Playgroud) rust ×1