MST

星途 面试题库

面试题:Rust结构体map函数在复杂数据处理中的应用

给定一个Rust结构体`Book`,包含字段`title`(字符串)、`author`(字符串)和`pages`(`u32`)。有一个`Book`结构体的向量`books`。请使用`map`函数创建一个新的向量,新向量中每个元素是一个元组,元组第一个元素是书的标题长度,第二个元素是作者名字长度,并且仅保留`pages`大于100的书进行处理。
32.4万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
struct Book {
    title: String,
    author: String,
    pages: u32,
}

fn main() {
    let books = vec![
        Book {
            title: "The Rust Programming Language".to_string(),
            author: "Steve Klabnik and Carol Nichols".to_string(),
            pages: 400,
        },
        Book {
            title: "Effective Rust".to_string(),
            author: "Joshua Nelson".to_string(),
            pages: 200,
        },
        Book {
            title: "Learning Rust with Entirely Too Many Linked Lists".to_string(),
            author: "Nicolai M. Josuttis".to_string(),
            pages: 50,
        },
    ];

    let new_books = books.into_iter()
                         .filter(|book| book.pages > 100)
                         .map(|book| (book.title.len(), book.author.len()))
                         .collect::<Vec<_>>();

    println!("{:?}", new_books);
}