Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I implement Into<MyType> for &str

Tags:

rust

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 }
}
like image 959
brandonchinn178 Avatar asked Jul 29 '15 04:07

brandonchinn178


1 Answers

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

like image 138
llogiq Avatar answered Oct 24 '22 00:10

llogiq