MST

星途 面试题库

面试题:Rust迭代器模式之复杂转换

假设有一个字符串`Vec<String>`,每个字符串代表一个人的信息,格式为`姓名,年龄,职业`。请使用Rust迭代器模式,将其转换为一个`Vec<(String, u32, String)>`,即解析出每个人的姓名、年龄和职业,并过滤掉年龄小于18岁的人。要求写出完整的代码实现以及必要的错误处理。
41.8万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
fn main() {
    let people_info: Vec<String> = vec![
        "Alice,25,Engineer".to_string(),
        "Bob,15,Student".to_string(),
        "Charlie,30,Doctor".to_string(),
    ];

    let result: Result<Vec<(String, u32, String)>, &'static str> = people_info
        .into_iter()
        .filter_map(|info| {
            let parts: Vec<&str> = info.split(',').collect();
            if parts.len() != 3 {
                return None;
            }
            let age = parts[1].parse::<u32>().ok()?;
            if age < 18 {
                return None;
            }
            Some((parts[0].to_string(), age, parts[2].to_string()))
        })
        .collect();

    match result {
        Ok(parsed_people) => {
            println!("Parsed people: {:?}", parsed_people);
        }
        Err(e) => {
            println!("Error: {}", e);
        }
    }
}
  1. 代码说明
    • 首先定义了一个people_infoVec<String>,包含一些人的信息。
    • 使用into_iterVec<String>转换为迭代器。
    • filter_map方法对每个字符串进行处理,先使用split(',')将字符串按逗号分割成&strVec
    • 检查分割后的部分数量是否为3,如果不是则返回None
    • 尝试将年龄部分解析为u32,如果解析失败返回None
    • 检查年龄是否小于18岁,如果是则返回None
    • 如果所有检查通过,将解析出的姓名、年龄和职业以(String, u32, String)的形式返回。
    • 最后使用collect将迭代器收集为Result<Vec<(String, u32, String)>, &'static str>,并通过match处理结果。如果成功,打印解析后的人员信息;如果失败,打印错误信息。