我試圖將&strs( &[&str]) 切片中的每個元素連接到一個擁有的String. 例如,我想&['Hello', ' world!']變成"Hello world!".
我試圖通過將切片轉換為迭代器,然后映射迭代器并將每個&str轉換為擁有的String,然后將它們全部收集到 aVec<String>和 running來做到這一點.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`.
它說我不能收集到 aVec<String>因為迭代器不是 a String,但我認為我已經將它轉換為 a Stringwith .map(|s| s.to_owned())。
我怎樣才能解決這個問題?我也是生銹的新手,所以有人可以解釋我做錯了什么會非常有幫助。
uj5u.com熱心網友回復:
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進入:String
a.into_iter().map(|s| s.to_string()).collect::<String>()
uj5u.com熱心網友回復:
有方法join和concat切片直接,所以你可以寫:
fn concat_str(a: &[&str]) -> String {
a.concat()
}
為您提供所需的輸出
uj5u.com熱心網友回復:
fn concat_str(a: &[&str]) -> String {
a.iter()
.cloned()
.collect()
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/531133.html
標籤:细绳向量锈迭代器类型转换
