【发布时间】:2014-11-23 17:56:14
【问题描述】:
我有以下问题:我有一个从缓冲区解析并包含对该缓冲区的一些引用的数据结构,因此解析函数看起来像
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}
}
不起作用,因为 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
}
为了避免在解析Bar 后移动缓冲区,但我不能这样做,因为必须一次性初始化整个BarWithBuf 结构。
现在我怀疑我可以使用unsafe 代码来部分构造结构,但我宁愿不这样做。
解决这个问题的最佳方法是什么?我需要不安全的代码吗?如果我这样做,在这里这样做是否安全?还是我完全走错了轨道,有更好的方法将数据结构及其底层缓冲区联系在一起?
【问题讨论】:
-
我从来没有想过是否可以在没有不安全代码的情况下对结构的其他成员进行内部引用。我看不出借用检查器如何跟踪像这样的借用...
-
这个问题已经够老了,我不想将其作为重复项关闭,但大多数访问此问题的人可能应该查看Why can't I store a value and a reference to that value in the same struct?。
标签: rust