9

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 }
}
Community
  • 1
  • 1
brandonchinn178
  • 519
  • 3
  • 20
  • 2
    (For converting from strings you should normally use the [`FromStr`](http://doc.rust-lang.org/std/str/trait.FromStr.html) trait; the method [`str.parse()`](http://doc.rust-lang.org/std/primitive.str.html#method.parse) will then also be able to produce your type. If you have a type that can be converted from a string without the possibility of errors, ignore this advice.) – Chris Morgan Jul 29 '15 at 04:58
  • Well the thing is that I want `new` to be able to take arguments that convert to `MyType`, for example. The emphasis is not on converting from strings, it's from converting strings to my type – brandonchinn178 Jul 29 '15 at 06:28

1 Answers1

8

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

llogiq
  • 13,815
  • 8
  • 40
  • 72
  • Ah yes `From<&str>` worked perfectly, and it makes sense because `impl From<&str> for Bar` doesn't have the orphan impl issue as before. Thanks! – brandonchinn178 Jul 29 '15 at 06:32
  • See also [When should I implement std::convert::From vs std::convert::Into?](http://stackoverflow.com/q/29812530/155423). – Shepmaster Jul 29 '15 at 14:01