MST

星途 面试题库

面试题:Rust中函数参数引用生命周期匹配问题

假设有一个Rust函数`fn longest<'a>(x: &'a str, y: &'a str) -> &'a str`,它返回两个字符串切片中较长的那个。请解释这里`'a`生命周期参数的作用,并且如果有一个函数`fn print_longest(x: &str, y: &str)`,该函数调用`longest`并打印结果,在`print_longest`函数中如何正确声明和使用`longest`函数?
42.9万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
  1. 'a生命周期参数的作用

    • 在Rust中,所有引用都有一个生命周期,即引用保持有效的作用域。'a生命周期参数在这里用于明确函数longest中输入参数xy以及返回值之间的生命周期关系。
    • 它表示xy和返回值的生命周期至少为'a,意味着返回值的生命周期与xy中生命周期较短的那个相同。这样可以确保返回的切片在调用者使用它的时候仍然有效,避免悬垂引用(dangling reference)的问题。例如,如果x的生命周期较短,当x超出其作用域时,返回值如果不是基于'a(也就是x的较短生命周期)来确定,可能会指向无效的内存。
  2. print_longest函数中声明和使用longest函数

fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() > y.len() {
        x
    } else {
        y
    }
}

fn print_longest(x: &str, y: &str) {
    let result = longest(x, y);
    println!("The longest string is: {}", result);
}

print_longest函数中,不需要再次显式声明longest函数的'a生命周期参数。因为Rust的生命周期省略规则可以自动推断出正确的生命周期。当调用longest(x, y)时,编译器会根据xy的实际生命周期来推断longest函数所需的'a生命周期,使得代码简洁且安全。