Rust 对相同/包含结构中的字段的引用

Rust 对相同/包含结构中的字段的引用,rust,Rust,我创建了这个简单的示例来模拟程序中引用发生的情况 struct Child {} struct Parent<'a> { child: &'a Child } struct Family { child: Box<Child>, parents: Vec<Box<dyn Any>> } fn main() { let child = Box::new(Child {}); let mut fam

我创建了这个简单的示例来模拟程序中引用发生的情况

struct Child {}

struct Parent<'a> {
    child: &'a Child
}

struct Family {
    child: Box<Child>,
    parents: Vec<Box<dyn Any>>
}

fn main() {
    let child = Box::new(Child {});
    let mut family = Family { child, parents: vec![] }; // child was moved to the family

    let parent = Box::new(Parent { child: &family.child }); // Parent accepts reference to family's child

    family.parents.push(parent); // Now parent was moved to the family.
    // So Family owns both: child and parent, 
    // so reference to the child in the parent will be correct during
    // lifetime of family
}

在任何和框中使用
dyn都是有意的-它模拟了我的程序中发生的情况。

您似乎有两个不相关的问题:

struct Child {}

struct Parent<'a> {
    child: &'a Child
}

struct Family {
    child: Box<Child>,
    parents: Vec<Box<dyn Any>>
}

fn main() {
    let child = Box::new(Child {});
    let mut family = Family { child, parents: vec![] }; // child was moved to the family

    let parent = Box::new(Parent { child: &family.child }); // Parent accepts reference to family's child

    family.parents.push(parent); // Now parent was moved to the family.
    // So Family owns both: child and parent, 
    // so reference to the child in the parent will be correct during
    // lifetime of family
}
1. <代码>父项
未实现任何dyn 尽管有名称,但并非所有类型都实现了
Any
特性,如
std::Any
中所述:

大多数类型实现
Any
。但是,任何包含非静态引用的类型都不会

因此,您的
父结构
无法实现
任何
(除非它被限制为仅具有
静态
子结构)。正如您所说的
dyn Any
来自程序的其余部分,很难给出修复建议

2.将值和对该值的引用存储在同一结构中 这是以前问过的,有一个问题

自引用结构的常见问题是,如果不使引用无效,就无法移动它们


但是,在某些情况下,我们可以安全地移动自引用结构,例如当引用的值被
ed(如您的
系列
)时,只要框中的值从未移动。链接到的答案涵盖了这个案例,并列出了可能的解决方法。

可能有一个重复的答案,我看到了这个问题。看起来很相似,但我认为情况并非如此:我有不同的错误,引用的对象存储在堆中,而不是建议的答案中的堆栈中。我实际上只是编辑我的注释,说我看到您有不同的错误,因此,可能情况不一样。链接的答案特别涉及当您的值在堆上时如何绕过“过度热心”的借用检查器