Any ideas why this fails with a None type?

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);

}

(Playground)

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);
2 Likes

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!

1 Like

To create None: Option<T>, you can use Option::<T>::None.

6 Likes

You can also do None::<T>

7 Likes

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 :slight_smile:

2 Likes

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.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.