Can Rust optimize out calls to `into()`, for example in constructors?
16:23 12 Aug 2026

I like to write constructors like this:

struct Foo {
    x: String,
    y: String,
}

impl Foo {
    fn new, Y: Into>(x: X, y: Y) -> Self {
        Self {
            x: x.into(),
            y: y.into(),
        }
    }

    // or this, but I know it makes it impossible to use the turbofish (::<>) syntax
    // fn new(x: impl Into, y: impl Into) -> Self {
    //     Self {
    //         x: x.into(),
    //         y: y.into(),
    //     }
    // }
}

which makes it easy to write Foo::new("bar", "baz").

Into for String just returns the original string unchanged, per this blanket implementation in standard library.

If I were to do Foo::new(String::new(), String::new()), I can see that there's no need to call .into() since these values are already strings. During monomorphization, can the compiler detect this and remove the calls to .into() for this specific case? Or, does that depend on whether my new() method is marked as #[inline]?

As a secondary question, is it bad practice to write constructors like this? I'm aware that it can bloat the code because the body is copied for each set of generics, but it just makes constructing objects (i.e. in tests) so easy

rust optimization