MST

星途 面试题库

面试题:Rust 生命周期标注:结构体中的复杂生命周期关系

定义一个 Rust 结构体 `Container`,它包含两个成员变量 `a` 和 `b`,分别是对不同字符串切片的引用。再定义一个方法 `combine`,该方法返回一个新的字符串切片,它是 `a` 和 `b` 连接后的结果。请正确标注结构体和方法的生命周期。另外,编写测试代码确保方法在各种情况下都能正确工作。 ```rust // 请在此处补充结构体定义及生命周期标注 struct Container { // 补充成员变量声明及生命周期标注 } // 请在此处补充方法定义及生命周期标注 impl Container { fn combine(&self) -> &str { // 实现字符串连接并返回切片 "" } } ```
19.8万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
// 请在此处补充结构体定义及生命周期标注
struct Container<'a> {
    // 补充成员变量声明及生命周期标注
    a: &'a str,
    b: &'a str,
}

// 请在此处补充方法定义及生命周期标注
impl<'a> Container<'a> {
    fn combine(&self) -> &'a str {
        // 实现字符串连接并返回切片
        let mut result = String::new();
        result.push_str(self.a);
        result.push_str(self.b);
        &result[..]
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_combine() {
        let container = Container {
            a: "Hello, ",
            b: "world!",
        };
        let combined = container.combine();
        assert_eq!(combined, "Hello, world!");
    }
}