Generic over all types that can be converted to another?

Hello dear Rustlang people,

I wanted to write something along the lines of

enum What {
    Nothing(i32),
}

impl <'a, T: Into<&'a str>>From<&'a T> for What {
    fn from(s: &T) -> Self {
        Self::Nothing(str::parse::<i32>(s.into()).unwrap())
    }
}

So, I want to use From on anything that can be converted into a &str. Is it possible? Does it make sense? It's entirely possible that it doesn't.

Currently, the error message this gives is the trait std::convert::From<&T> is not implemented for &str.

Currently the bound is T: Into<&'a str>, instead of &T: Into<&'a str>.

Had to fiddle around a bit with the trait (used AsRef instead), but came up with this:

enum What {
    Nothing(i32),
}

impl<T> From<&T> for What
where
    T: AsRef<str>
{
    fn from(s: &T) -> Self {
        Self::Nothing(str::parse::<i32>(s.as_ref()).unwrap())
    }
}

playground

1 Like

This is great, thanks very much!

Don't count too hard on that syntax changing any time soon :wink: