fn wrapped_string<S:Into<String>>(input: Option<S>) -> Option<String> {
input.map(|s| s.into())
}
fn main() {
let full_name = "John Doe";
let example = wrapped_string(Some(full_name));
println!("{:?}", example);
let empty = wrapped_string(None);
println!("{:?}", empty);
}
Because the type T
of Option<T>
is unknown. It doesn't matter for your implementation, but in theory wrapped_string
can do totally different things depending on T
, even when it is None
.
This change should work:
let empty = wrapped_string::<String>(None);
Ahh, of course. I didn't really think about it from the calling perspective. I was just puzzled on why it would build/run fine with a Some, but not with a None. Thanks!
To create None: Option<T>
, you can use Option::<T>::None
.
You can also do None::<T>
Oh, I didn't know that was even possible; that seems like a weird place to take a type argument (it is not consistent with associated items turbofish), but it does have the advantage of being significantly shorter
Yeah, it looks kinda weird, but you can do this with any enum.
Instead of Enum::<TypeParameter, ...>::Variant
you can do Variant::<TypeParameter, ...>
Provided that you have the Variant
in scope.
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.