MST

星途 面试题库

面试题:Rust中特征对象与生命周期的复杂交互

定义多个结构体,如`Parent`、`Child1`、`Child2`,`Child1`和`Child2`都实现一个共同的特征`CommonTrait`。`Parent`结构体包含一个`Vec<Box<dyn CommonTrait>>`成员。编写一个函数`create_parent`,该函数接收不同生命周期的`Child1`和`Child2`实例,并将它们放入`Parent`的`Vec`成员中,最后返回`Parent`实例。要求正确处理好所有的生命周期标注,保证代码不会出现悬垂引用等问题。
48.8万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
trait CommonTrait {}

struct Parent {
    children: Vec<Box<dyn CommonTrait>>,
}

struct Child1;
struct Child2;

impl CommonTrait for Child1 {}
impl CommonTrait for Child2 {}

fn create_parent<'a, 'b>(child1: &'a mut Child1, child2: &'b mut Child2) -> Parent {
    let mut children = Vec::new();
    children.push(Box::new(child1));
    children.push(Box::new(child2));

    Parent {
        children,
    }
}