< 返回版块

ilp64 发表于 2020-12-17 15:54

Tags:ownership

ParentChild结构体,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);
}

评论区

写评论
lithbitren 2020-12-18 17:06

跟着编译器改也改得成这样,甚至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); }


作者 ilp64 2020-12-17 16:25

谢谢大佬

--
👇
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 2020-12-17 16:18
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);
}
1 共 3 条评论, 1 页