fn parse_bar<'a>(buf: &'a [u8]) -> Bar<'a>
目前为止,一切都很好。不过,为了避免某些生命周期问题,我想将数据结构和底层缓冲区放入一个结构体中,如下所示:
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
被移动了,但我们又借用它进行解析。
我觉得可以尝试类似以下的操作:
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
结构必须一次性初始化。
现在我怀疑我可以使用unsafe
代码部分构造结构体,但我宁愿不这样做。
如何解决这个问题?我需要使用不安全的代码吗?如果需要,这里这样做是否安全?或者我完全走错了路,有更好的方法将数据结构和其基础缓冲区绑定在一起吗?