MST
星途 面试题库

面试题:Rust函数返回复杂结构中的引用管理

假设有一个结构体 `Container`,它包含一个 `Vec<i32>` 字段和一个 `i32` 字段。编写一个函数,该函数接收 `Container` 的引用,在 `Vec<i32>` 中找到最大值,如果最大值大于 `Container` 的 `i32` 字段值,则返回最大值的引用,否则返回 `Container` 中 `i32` 字段的引用。请确保引用的生命周期符合Rust的规则,避免悬垂引用。
25.9万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
struct Container {
    data: Vec<i32>,
    value: i32,
}

fn find_max<'a>(container: &'a Container) -> &'a i32 {
    let max_in_vec = container.data.iter().max();
    match max_in_vec {
        Some(max) if *max > container.value => max,
        _ => &container.value,
    }
}