In #rust #rustlang, in trait implementations, is there a reason to use the raw type instead of the Into type? Does the Into version just save me from having to type ".into()" or is there more to it?

For example:

impl<'a> From<&'a str> for Foo<'a>

versus

impl<'a, T: Into<&'a str>> From<T> for Foo<'a>

@livingcoder Working with Into instead of the raw type is sometimes unneeded complexity. Personally, I only use it when I want to save the into().

Defaulting to raw types is better to avoid conflicts. Let's say you implement From<T> where T: Into<U>. If V implements Into<U>, then you can not implement a specific From<V> anymore.

Rust Playground

A browser interface to the Rust compiler to experiment with the language

@mo8it That's interesting. Thank you. Hmm. I would hope that the impl block that fails wouldn't actually be necessary/needed given the existing impl block... but I guess you never know what someone may want functionality-wise for special cases.

@livingcoder One thing to note is that if you use traits like `Into` and `AsRef`, you might end up with a bunch of unnecessarily duplicated code bloating up your binary size.

You can avoid this with tricks like

fn do_thing_inner(x: Foo) {
// Implementation goes here...
}

pub fn do_thing<T: Into<Foo>>(x: T) {
do_thing_inner(x.into());
}

This trick is used in the standard library, for example: https://doc.rust-lang.org/1.70.0/src/std/fs.rs.html#325-330

fs.rs - source

Source of the Rust file `library/std/src/fs.rs`.

@TDplay Thanks for the reply, but it looks like an even better implementation is to include the specific function inside of the generic function.
Here is the post from @alilleybrinker where he shares a link to a great blog post about this topic.
https://hachyderm.io/@alilleybrinker/110628650549424303
Andrew Lilley Brinker (@[email protected])

@[email protected] 1. Generic API’s are harder to teach and learn. 2. Unless you manually outline the non-generic version, you can pay a substantial monomorphization cost. See: https://www.possiblerust.com/pattern/non-generic-inner-functions

Hachyderm.io