代码之家  ›  专栏  ›  技术社区  ›  Michael M.

将`&str`的切片连接到所拥有的`String中`

  •  1
  • Michael M.  · 技术社区  · 2 年前

    我正在尝试将 &str s( &[&str] )变成一个单独拥有的 String 。例如,我想转 &['Hello', ' world!'] 进入 "Hello world!"

    我试图通过将切片转换为迭代器来实现这一点,然后在迭代器上映射并转换每个 &str 变成一个拥有的 一串 ,然后将它们全部收集到 Vec<String> 和跑步 .join("") ,但我一直收到一个类型错误。

    这是我的代码:

    fn concat_str(a: &[&str]) -> String {
        a.into_iter().map(|s| s.to_owned()).collect::<Vec<String>>().join("")
    }
    
    fn main() {
        let arr = ["Dog", "Cat", "Bird", "Lion"];
    
        println!("{}", concat_str(&arr[..3])); // should print "DogCatBird"
        println!("{}", concat_str(&arr[2..])); // should print "BirdLion"
        println!("{}", concat_str(&arr[1..3])); // should print "CatBird"
    }
    

    这是我得到的编译器错误:

    error[E0277]: a value of type `Vec<String>` cannot be built from an iterator over elements of type `&str`
        --> code.rs:2:38
         |
    2    |     a.into_iter().map(|s| s.to_owned()).collect::<Vec<String>>().join("")
         |                                         ^^^^^^^ value of type `Vec<String>` cannot be built from `std::iter::Iterator<Item=&str>`
         |
         = help: the trait `FromIterator<&str>` is not implemented for `Vec<String>`
    note: required by a bound in `collect`
        --> /Users/michaelfm1211/.rustup/toolchains/stable-x86_64-apple-darwin/lib/rustlib/src/rust/library/core/src/iter/traits/iterator.rs:1780:19
         |
    1780 |     fn collect<B: FromIterator<Self::Item>>(self) -> B
         |                   ^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `collect`
    
    error: aborting due to previous error
    
    For more information about this error, try `rustc --explain E0277`.
    

    上面写着我不能收集 Vec<字符串> 因为迭代器不是 一串 ,但我以为我已经将其转换为 一串 具有 .map(|s| s.to_owned())

    我该怎么解决这个问题?我也是新手,所以如果有人能解释我做错了什么,那将是非常有帮助的。

    1 回复  |  直到 2 年前
        1
  •  3
  •   Mikdore    2 年前

    into_iter 将生成一个迭代器 Item=&&str 。在您的地图中, .to_owned() 将其转换为 &str ,这不起作用。有几种方法可以解决这个问题,你可以使用 .copied .cloned 获得 &str :

    a.into_iter().copied().map(|s| s.to_owned()).collect::<Vec<String>>().join("")
    // or
    a.into_iter().cloned().map(|s| s.to_owned()).collect::<Vec<String>>().join("")
    

    或者你可以使用 .to_string() 获得 String 直接:

    a.into_iter().map(|s| s.to_string()).collect::<Vec<String>>().join("")
    

    注意,你也可以 collect 变成 一串 当您不需要直接使用分隔符时:

    a.into_iter().map(|s| s.to_string()).collect::<String>()