面试题答案
一键面试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
函数中,num1
、num2
、str1
、str2
的生命周期都长于函数调用和对返回值的使用,因此不会出现生命周期相关的错误。