4

Should I be writing:

impl<'a> From<&'a Type> for OtherType

Or should it be

impl From<Type> for OtherType

I'm having a difficult time finding the answer, perhaps due to a vocabulary failure on my part. I really don't particularly care about the reference-ness/value-ness of the argument.

In C++, I would define the function over/method on values and calling it on const references.

Is there an automatic derivation from impl Trait<Type> to impl<'a> Trait<&'a Type>?

Shepmaster
  • 326,504
  • 69
  • 892
  • 1,159
jcc333
  • 719
  • 4
  • 15
  • 1
    This simply isn't answerable in its current form; it depends on why the trait needs a type parameter in the first place. Do you mean specifically the [operator traits](https://doc.rust-lang.org/std/ops/) like `Add`, `Sub`, `BitAnd`, etc.? – trent Jan 13 '18 at 23:39
  • Edited to *try* to clarify, but I'll be honest, coming from a functional programming / c++ background some of this stuff is still fairly inscrutable so I'm kind of shooting in the dark – jcc333 Jan 13 '18 at 23:59

1 Answers1

5

Should Rust implementations of From/TryFrom target references or values?

Yes, they should.

There's no trickery here: implement the traits to convert whatever types you have. If you have a String, implement it to convert from Strings. If you have a &str, implement it to convert from &strs. If you have both, implement it for both.

Is there an automatic derivation from impl Trait<Type> to impl<'a> Trait<&'a Type>?

No, and for good reason. For example, consider this conversion:

struct Filename(String);

impl From<String> for Filename {
    fn from(value: String) -> Filename {
        Filename(value)
    }
}

There's no obviously correct way for the compiler to implement that for a reference to a String. However, you can implement it yourself:

impl<'a> From<&'a str> for Filename {
    fn from(value: &'a str) -> Filename {
        String::into(value.to_owned())
    }
}

If you can't make use of the incoming allocation, then there's not much reason to accept the argument by value, so you might as well accept a reference. However, I'd say it's less common to use From for such conversions — not unheard of, though.

Shepmaster
  • 326,504
  • 69
  • 892
  • 1,159