更新时间:2022-12-08 16:20:55
我认为您是对的,没有不安全的代码就不可能做到这一点.我会考虑以下两个选项:
I think you're right in that it's not possible to do this without unsafe code. I would consider the following two options:
将 Bar
中的引用更改为索引.框内的内容不受借用保护,因此如果您不小心,索引可能会失效.但是,索引可能会以更清晰的方式传达引用的含义.
Change the reference in Bar
to an index. The contents of the box won't be protected by a borrow, so the index might become invalid if you're not careful. However, an index might convey the meaning of the reference in a clearer way.
将Box
移动到Bar
中,并添加一个函数buf() ->&[u8]
到 Bar
的实现;而不是引用,将索引存储在 Bar
中.现在 Bar
是缓冲区的所有者,因此它可以控制其修改并保持索引有效(从而避免选项 #1 的问题).
Move Box<[u8]>
into Bar
, and add a function buf() -> &[u8]
to the implementation of Bar
; instead of references, store indices in Bar
. Now Bar
is the owner of the buffer, so it can control its modification and keep the indices valid (thereby avoiding the problem of option #1).
根据下面 DK 的建议,将索引存储在 BarWithBuf
(或辅助结构 BarInternal
)中并添加函数 fn bar(&自我)->Bar
到 BarWithBuf
的实现,它会即时构造一个 Bar
.
As per DK's suggestion below, store indices in BarWithBuf
(or in a helper struct BarInternal
) and add a function fn bar(&self) -> Bar
to the implementation of BarWithBuf
, which constructs a Bar
on-the-fly.
这些选项中哪一个最合适取决于实际的问题上下文.我同意某种形式的逐个成员构造"结构在 Rust 中会非常有帮助.
Which of these options is the most appropriate one depends on the actual problem context. I agree that some form of "member-by-member construction" of structs would be immensely helpful in Rust.