I have got a problem with implement the convert string to vec function with trait.
Here is the error message:
error[E0277]: a value of type `Result<_, _>` cannot be built from an iterator over elements of type `char`
--> src/main.rs:7:28
|
7 | match self.chars().collect() {
| ^^^^^^^ value of type `Result<_, _>` cannot be built from `std::iter::Iterator<Item=char>`
|
= help: the trait `FromIterator<char>` is not implemented for `Result<_, _>`
= help: the trait `FromIterator<Result<_, _>>` is implemented for `Result<_, _>`
= help: for that trait implementation, expected `Result<_, _>`, found `char`
note: the method call chain might not have had the expected associated types
--> src/main.rs:7:20
|
7 | match self.chars().collect() {
| ---- ^^^^^^^ `Iterator::Item` is `char` here
| |
| this expression has type `&&str`
note: required by a bound in `collect`
--> /playground/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/traits/iterator.rs:2050:19
|
2050 | fn collect<B: FromIterator<Self::Item>>(self) -> B
| ^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `Iterator::collect`
And the code as below:
trait StringObject {
fn convert_to_vec(&self) -> Result<Vec<char>,&'static str>;
}
impl StringObject for &str {
fn convert_to_vec(&self) -> Result<Vec<char>, &'static str> {
match self.chars().collect() {
Ok(c) => Ok(c),
Err(e) => Err(e),
}
}
}
fn main() {
let sobje = "teststringe";
let array:Vec<char> = sobje.chars().collect();
// let sobjechars = sobje.convert_to_vec().unwrap();
println!("sobjechars={:?}",array);
}
>Solution :
chars() of a &str has no error conditions whatsoever, it’s elements are char, so you can just collect into a Vec<char> directly and wrap it in Ok:
impl StringObject for &str {
fn convert_to_vec(&self) -> Result<Vec<char>, &'static str> {
Ok(self.chars().collect())
}
}
To collect into a Result and match on Ok or Err the items of an iterator have to be Results themselves.