MST

星途 面试题库

面试题:Rust函数的泛型与生命周期

编写一个泛型函数,该函数接受两个相同类型的参数,并返回其中较长的字符串(如果参数是字符串类型)或者较大的数字(如果参数是数字类型)。同时,要正确处理参数可能涉及的生命周期问题,解释为什么这样处理。
14.7万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
fn longer_or_larger<T: std::cmp::PartialOrd + std::fmt::Debug>(a: &T, b: &T) -> &T {
    if let Some(a_str) = a as &str {
        if let Some(b_str) = b as &str {
            if a_str.len() >= b_str.len() {
                a
            } else {
                b
            }
        } else {
            panic!("Both arguments must be of the same type.");
        }
    } else if let Some(a_num) = a as &i32 {
        if let Some(b_num) = b as &i32 {
            if a_num >= b_num {
                a
            } else {
                b
            }
        } else {
            panic!("Both arguments must be of the same type.");
        }
    } else {
        panic!("Unsupported type. Only strings and numbers (i32 for simplicity) are supported.");
    }
}

生命周期处理解释:函数参数使用&T,这意味着函数接受借用的参数。返回值&T也表示返回的是借用的值,其生命周期与传入的借用参数相关。这样处理生命周期,使得返回值的生命周期不会超过传入参数的生命周期,避免了悬垂引用的问题。函数内部在比较时,直接操作借用的值,没有进行值的所有权转移,进一步保证了生命周期的正确性。

在实际使用中,调用者要确保传入的参数的生命周期足够长,以涵盖函数调用以及使用返回值的代码块。例如:

fn main() {
    let num1 = 10;
    let num2 = 20;
    let result_num = longer_or_larger(&num1, &num2);
    println!("The larger number is: {:?}", result_num);

    let str1 = "hello";
    let str2 = "world";
    let result_str = longer_or_larger(&str1, &str2);
    println!("The longer string is: {:?}", result_str);
}

在上述main函数中,num1num2str1str2的生命周期都长于函数调用和对返回值的使用,因此不会出现生命周期相关的错误。