'Why does Option<&str>::cloned() not produce an Option<String>?
I have an Option<&str> and I would like to end up with an Option<String>. For other types, Option::cloned would be an easy way to do that. The docs even say:
pub fn cloned(self) ->
Option<T>Maps an
Option<&T>to anOption<T>by cloning the contents of the option.
However, trying this actually results in a compile error:
fn main() {
let unowned_str_maybe: Option<&str> = Some("abc");
let owned_str_maybe: Option<String> = unowned_str_maybe.cloned(); // <-- unsatisfied trait bounds
println!("{:?}", owned_str_maybe);
}
/* Compile error is:
error[E0599]: the method `cloned` exists for enum `Option<&str>`, but its trait bounds were not satisfied
--> src/main.rs:5:61
|
5 | let owned_str_maybe: Option<String> = unowned_str_maybe.cloned(); // <-- unsatisfied trait bounds
| ^^^^^^ method cannot be called on `Option<&str>` due to unsatisfied trait bounds
|
= note: the following trait bounds were not satisfied:
`str: Sized`
`str: Clone`
`Option<&str>: Iterator`
which is required by `&mut Option<&str>: Iterator`
*/
Using a more verbose (less idiomatic?) construction of .map(|x| x.to_string()) does compile. Why does Option::cloned not work for converting &str to String?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
