MST

星途 面试题库

面试题:Rust函数中多个引用生命周期管理及结构体关联

定义一个结构体`Container`,它包含两个字符串切片`str1`和`str2`。再定义一个函数`fn combine<'a, 'b>(container: &'a Container, new_str: &'b str) -> &'a str`,该函数根据一定逻辑(例如`str1`长度大于`str2`则返回`str1`,否则返回`new_str`)返回一个字符串切片。请正确实现这个结构体和函数,并详细说明其中生命周期参数`'a`和`'b`的关系及约束。
16.9万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
// 定义结构体Container
struct Container {
    str1: Vec<String>,
    str2: Vec<String>,
}

// 实现函数combine
fn combine<'a, 'b>(container: &'a Container, new_str: &'b str) -> &'a str {
    if container.str1.len() > container.str2.len() {
        &container.str1[0]
    } else {
        new_str
    }
}

生命周期参数'a'b的关系及约束

  • 'a:表示container这个引用的生命周期。这意味着函数返回的字符串切片的生命周期至少和container一样长。因为container可能包含内部数据(如str1str2),返回的切片可能是指向container内部的字符串,所以返回值的生命周期必须受限于container的生命周期。
  • 'b:表示new_str这个引用的生命周期。new_str是一个独立传入的字符串切片,它的生命周期独立于container
  • 函数返回值的生命周期为'a,这意味着返回值的生命周期取决于container的生命周期,而不是new_str的生命周期。在if - else语句中,如果返回container内部的str1中的元素,其生命周期自然受限于container(为'a);如果返回new_str,由于返回值生命周期被指定为'a,那么要求'b必须至少和'a一样长(即'b: 'a),这样才能保证在container的生命周期内,new_str也是有效的。如果不满足'b: 'a,编译器会报错,因为可能出现返回一个比container生命周期更短的new_str,导致悬垂指针问题。