迫使结构超过另一个结构
我有两个结构。第一个“父”结构是需要明确清理的资源,我通过得出drop
特征来处理的资源。第二个“儿童”结构是从父结构中检索出来的,并且所述资源尚未被交易为有效。
换句话说,任何父母的实例都必须超过其子女。
我的解决方案使用参考来使借用检查器执行此规则。
struct Parent {
// Private resource data.
}
impl Parent {
fn new() -> Self {
Parent {}
}
fn new_child(&self) -> Child {
return Child { _parent: self };
}
}
impl Drop for Parent {
fn drop(&mut self) {
// Do some cleanup after which no instance of Child will be valid.
}
}
struct Child<'a> {
_parent: &'a Parent,
// Private data.
}
impl<'a> Child<'a> {
fn hello(&self) {
println!("Hello Child!");
}
}
fn main() {
let parent = Parent::new();
let child = parent.new_child();
child.hello();
// Fails to compile with the following line uncommented (as intented).
// drop(parent);
// child.hello();
}
这有效,但是child
&nbsp;实际上并不需要了解其父母。我想将参考字段替换为phantomdata
:
struct Child<'a> {
_parent: PhantomData<&'a Parent>,
// Private data.
}
但是,在这种情况下,我如何“绑定” _Parent
&nbsp; in parent in
parent: :new_child
?
I have two structs. The first, "parent" struct holds a resource that needs explicit cleanup, which I am handling by deriving the Drop
trait. The second, "child" struct is retrieved from the parent struct and needs that said resource hasn't been deallocated to be valid.
In other words, any parent instance must outlive its children.
My solution uses references to make the borrow checker enforce this rule.
struct Parent {
// Private resource data.
}
impl Parent {
fn new() -> Self {
Parent {}
}
fn new_child(&self) -> Child {
return Child { _parent: self };
}
}
impl Drop for Parent {
fn drop(&mut self) {
// Do some cleanup after which no instance of Child will be valid.
}
}
struct Child<'a> {
_parent: &'a Parent,
// Private data.
}
impl<'a> Child<'a> {
fn hello(&self) {
println!("Hello Child!");
}
}
fn main() {
let parent = Parent::new();
let child = parent.new_child();
child.hello();
// Fails to compile with the following line uncommented (as intented).
// drop(parent);
// child.hello();
}
This works, but the Child
doesn't actually need to know its parent. I thought to replace the reference field with a PhantomData
:
struct Child<'a> {
_parent: PhantomData<&'a Parent>,
// Private data.
}
But in this case, how can I "bind" _parent
to the parent instance, in Parent::new_child
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以做以下操作:
这应该给您带来所需的行为。
You could do the following:
This should give you the desired behavior.