如何使用 map 转换 Rust 中的字符串向量,然后使用 flat_map 将字符串连接到一行中?

问题描述 投票:0回答:1

我正在为迭代器章节进行第二级的沙沙声。

我找到了以下第3步的解决方案,现在我想链接map和flat_map。

// Step 3.
// Apply the `capitalize_first` function again to a slice of string slices.
// Return a single string.
// ["hello", " ", "world"] -> "Hello World"
pub fn capitalize_words_string(words: &[&str]) -> String {
    let capitalized: Vec<String> = words.iter().map(|word| capitalize_first(&word)).collect();
    capitalized.iter().flat_map(|s| s.chars()).collect()
}

然而,这种天真的做法...

words.iter().map(|w| capitalize_first(w)).flat_map(|s| s.char_indices()).collect()

我收到这些编译器错误,我不明白:

36   |     words.iter().map(|w| capitalize_first(w)).flat_map(|s| s.char_indices()).collect()
     |                                                                              ^^^^^^^ value of type `String` cannot be built from `std::iter::Iterator<Item=(usize, char)>`
36   |     words.iter().map(|w| capitalize_first(w)).flat_map(|s| s.char_indices()).collect()
     |     ----- ------ ---------------------------- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `Iterator::Item` changed to `(usize, char)` here
     |     |     |      |
     |     |     |      `Iterator::Item` changed to `String` here
     |     |     `Iterator::Item` is `&&str` here
     |     this expression has type `&[&str]`
rust iterator rust-rustlings
1个回答
0
投票

你真的需要专门使用

flat_map
吗?如果没有的话,就会这样做:

fn capitalize_words_strings(words: &[&str]) -> String {
    words.iter()
        .map(|word| capitalize_first(word))
        .collect()
}

如果你确实需要使用

flat_map
,你可以通过执行
flat_map
添加一个“noop”
std::iter::once()

fn capitalize_words_strings(words: &[&str]) -> String {
    words.iter()
        .map(|word| capitalize_first(word))
        .flat_map(|word| std::iter::once(word))
        .collect()
}
© www.soinside.com 2019 - 2024. All rights reserved.