有Parent
和Child
结构体,Parent
可以创建多个Child
,每个Child
里面持有创建者Parent
实例,并且Child
实例有方法可以获取Parent
实例。
下面是演示场景的问题代码,请大佬们指点一下这种场景的做法
struct Parent {
name: String,
}
impl Parent {
fn create_child(&self) -> Child {
Child {
id: get_id(),
parent: self,
}
}
}
struct Child {
id: u64,
parent: Parent,
}
impl Child {
fn get_parent(&self) -> Parent {
self.parent
}
}
fn main() {
let parent = Parent {
name: "xxx".to_string(),
};
let child1 = parent.create_child();
let child2 = parent.create_child();
let name1 = child1.get_parent().name;
let name2 = child2.get_parent().name;
assert_eq!(name1, name2);
}
1
共 3 条评论, 1 页
评论区
写评论跟着编译器改也改得成这样,甚至
fn get_parent(&self) -> &'a Parent
这里还可以省一个标记,不过还是搞不明白为啥一个需要标注一个不需要标注,几个变量的生命周期到底是什么关系。。编译器提示在创建child
的时候parent
必须要用引用,然后才有后来的标记,如果Parent
实现了拷贝是不是就可以不用引用了?不太懂望大佬解惑--
👇
xiaopengli89: ```rust struct Parent { name: String, }
impl Parent { fn create_child(&self) -> Child { Child { id: 1, parent: self, } } }
struct Child<'a> { id: u64, parent: &'a Parent, }
impl<'a> Child<'a> { fn get_parent(&self) -> &'a Parent { &self.parent } }
fn main() { let parent = Parent { name: "xxx".to_string(), }; let child1 = parent.create_child(); let child2 = parent.create_child(); let name1 = &child1.get_parent().name; let name2 = &child2.get_parent().name; assert_eq!(name1, name2); }
谢谢大佬
--
👇
xiaopengli89: ```rust struct Parent { name: String, }
impl Parent { fn create_child(&self) -> Child { Child { id: 1, parent: self, } } }
struct Child<'a> { id: u64, parent: &'a Parent, }
impl<'a> Child<'a> { fn get_parent(&self) -> &'a Parent { &self.parent } }
fn main() { let parent = Parent { name: "xxx".to_string(), }; let child1 = parent.create_child(); let child2 = parent.create_child(); let name1 = &child1.get_parent().name; let name2 = &child2.get_parent().name; assert_eq!(name1, name2); }