brandonchinn178
brandonchinn178

Reputation: 539

How do I implement Into<MyType> for &str

I have a custom type pub struct Foo and I'd like to be able to say strings can be converted to Foo types. I'm trying to do impl<'a> Into<Foo> for &'a str, but I know from this answer that I can't do that. What other options do I have?

For context, I'm trying to do something like

trait Foo {
    type ArgType;
    fn new<I: Into<Self::ArgType>>(arg: I) -> Self;
}

struct MyType;
impl Into<MyType> for str {
    fn into(self) -> MyType { MyType }
}

struct Bar;
impl Foo for Bar {
    type ArgType = MyType;
    fn new<I: Into<MyType>>(arg: I) -> Bar { Bar }
}

Upvotes: 9

Views: 2764

Answers (1)

llogiq
llogiq

Reputation: 14511

As Chris Morgan noted, FromStr is an option, From<&str> would be another. The latter would give you a builtin implementation of Into<Foo> for &str, too (because there is a blanket impl of Into<U> For T where U: From<T>).

Upvotes: 8

Related Questions