Impl mut and override for incremental, scoped reuse of existing impls

Summary

This proposal lets a downstream crate replace one method of an existing concrete impl while keeping the rest, via an opt-in impl mut marker and override blocks that forward unlisted methods to super.

Concretely, it adds two new items:

· impl mut Trait for Type { ... } marks an existing impl as open for override. · override Trait for Type { ... } creates a new implementation that only specifies the methods it changes; unlisted methods are implicitly forwarded to the override target.

Inside an override block, super refers to the override target's implementation, allowing reuse of the original behavior.

The goal is to let downstream crates incrementally modify an existing concrete impl without forking the crate, writing a newtype, or hand-writing forwarding boilerplate.

Motivation

Rust's existing reuse tools each have a gap:

· Composition/delegation: Can modify behavior, but requires manually forwarding every method of the wrapped impl. Changing one method still means writing N forwarding stubs. · Newtype: Requires a new type; all signatures at call sites change. · Trait default methods: Reuse is decided by the trait author, not by the consumer; you cannot replace one method of an already written concrete impl. · Macros: Generate code, but the result is independent code with no semantic link to the original impl. · Specialization: Solves overlap at the generic constraint level, not "replace one method of a specific concrete impl and keep the rest."

Concrete scenario: a third-party crate provides impl Parser for TheirType; one method has a bug or poor performance. Today the options are fork the crate, wrap it in a newtype and re-forward everything, or wait for upstream. There is no type-system-level way to say "use their impl, but replace this one method."

This proposal is that mechanism. It is intentionally small: it does not change the default reuse path (traits + composition remain the norm), does not introduce inheritance trees, and does not pass implicit state between types.

Detailed design

  1. impl mut — opt-in extension point. impl mut A for B { ... } declares the block open for override. A plain impl cannot be overridden.
  2. override — partial replacement with implicit forwarding.
    override A for B {
        fn foo(&self) { /* new behavior, may call super.foo() */ }
        // bar, baz, ... automatically forwarded to the override target
    }
    
    Only listed methods are replaced; unlisted methods forward to the override target.
  3. super — reuse the override target. super refers to the implementation named as the override target (the specific impl mut or override it was declared against), not a type hierarchy. super.foo() calls the target's foo. It appears in expression position inside override methods; super elsewhere remains the path keyword.
  4. Override chains form a DAG. override may target another override (see rule 6). Two overrides with the same target are allowed provided they are declared in different paths. super resolves along the declaration edge one step.
  5. Resolution scope is the declaration site. A call to T::method() inside a function resolves against the impls/overrides visible where the function is declared, not where it is called. This confines an override's effect to the declaring module and keeps coherence and monomorphization unaffected by call-site imports.
  6. Overrides are not re-overridable by default. An override can only be overridden if declared override mut. This mirrors the opt-in philosophy of impl mut.
  7. Orphan-rule exemption, disambiguated by paths. override is exempt from the orphan rule. Conflicts are resolved by import: use path::impl selects the base impl, use path::override selects an override. The same (Trait, Type) pair may not appear twice under one path.
  8. Missing mut recovery. If a downstream crate wants to override an override that was not marked mut, it copies that override into its own path and declares a fresh override. The new node is independent of the original; no special mechanism needed.

Drawbacks

· Trait resolution complexity. The resolver must incorporate "overrides visible at the declaration site" into trait solving. This is the main engineering cost; rule 5 deliberately fixes the scope to keep it bounded. · Readability of chains. With a DAG and implicit forwarding, "which impl actually runs" needs tooling (e.g., an override-chain expansion). This is a tooling concern, not a semantic one. · Proliferation risk. Authors may mark every impl mut "just in case," diluting the meaning of the extension point. A lint or community convention could mitigate this.

Rationale and alternatives

· Why not specialization? Specialization decides overlap among impls with different generic bounds; it does not let a consumer replace one method of a specific concrete impl while retaining the rest. The two are complementary. · Why not scope-based impl selection? Scoped-impl proposals address orphan-rule bypass and impl selection per scope, and typically change the type's identity. This proposal keeps type identity and adds incremental modification with super reuse. · Why impl mut rather than "any impl is overridable"? Opt-in prevents third parties from silently altering a library's behavior; the library author decides whether an extension point exists.

Prior art

I am not aware of an accepted or open RFC matching this combination (impl mut + partial override + super reuse + declaration-site resolution). Scope-based impl proposals share the "disambiguate by path" idea but differ in purpose and semantics. Feedback on closer prior art is welcome — that is part of why this is a Pre-RFC.

Unresolved questions

  1. Keyword collision for super. super currently only appears in paths, and an override block's method body is an expression context, so the two usages likely do not collide syntactically. Preferred: keep super, resolved by context. Fallback if the parser or diagnostics object: a contextual keyword base, valid only inside override blocks.
  2. Naming. Should impl mut / override blocks be optionally nameable for better diagnostics and path imports, without forcing authors to pick names?
  3. Path-syntax ergonomics. Is use path::impl / use path::override acceptable, or does it need a dedicated syntax?
  4. Interaction with specialization and coherence. Does declaration-site resolution fully avoid interaction with the existing coherence model, or are there edge cases (e.g., associated type projection through an override)?
  5. Associated types. The sketch allows associated types to be overridden; projection through an override chain needs specification.
  6. Object safety and dyn. How do overrides interact with trait objects and vtable construction?

Conclusion

This is a small mechanism aimed at a specific gap: modifying an existing concrete impl incrementally, in a way that is explicit, scoped, and reuses the original via super. It does not replace composition or traits as the default reuse path. I am posting this as a Pre-RFC to validate that the gap is real, check for prior art, and get feedback on the resolution-scope question and the DAG semantics before considering a formal RFC.

Disclosure: The design and core ideas are mine. The English text of this post was drafted with AI assistance.

That's like specialization with all of its problems except with even more problems.

1 Like

I see no discussion of generic type parameters in here, which is required if you're going to justify this being sound when specialization isn't.

For example, if I have:

impl<T: SomeTrait> mut Trait for Struct<T>

what overrides can I write? override<T: SomeTrait> for Struct<T>? override<T: AnotherTrait> Trait for Struct<T>? Or even override Trait for Struct<u32>?

The details of the answer here really matter - this is where soundness holes were found in specialization, and trying to find ways to fix them is what's held up stabilizing specialization for so long.

I don't see a way to fix this feature that won't work for specialization. Like I said, this only adds problems (not saying this couldn't be nice).

I think this framing assumes the proposal competes with specialization. It doesn't. Specialization decides overlap between impls with different bounds. This proposal does method-level incremental replacement within a single generic family, with identical headers. They are orthogonal: replacing one method of an existing impl is not a weaker version of "more specific impl wins" — it's a different operation.

Concretely, the proposal distinguishes two kinds of override:

A. Same-family method replacement (allowed).

impl<T: SomeTrait> mut Trait for Struct<T> { ... }

override<T: SomeTrait> Trait for Struct<T> {
    fn foo(&self) { ... } // only foo replaced; the rest forward
}

The override's generic header must be identical to the target's: same parameter count, equivalent bounds. super resolves at each monomorphization to the target family's instance for that T — since the headers match, that instance always exists and is unique. No constraint solving, no overlap check.

B. Specialization-style override (not allowed).

override<T: AnotherTrait> Trait for Struct<T> { ... } // not allowed
override Trait for Struct<u32> { ... }                  // not allowed

Different bounds or a specific concrete type are out of scope. That is where specialization's soundness holes live, and this proposal does not attempt to solve them.

So the problems specialization has are not inherited here, because the territory where they arise is excluded by design. If someone believes A collapses into B in some concrete scenario, I'd genuinely like to see the case — that would be a real objection.

I see no discussion of generic type parameters in here, which is required if you're going to justify this being sound when specialization isn't.

You're right that the original post should have been explicit about this. The answer is that overrides are restricted to the same generic family as the target.

For:

impl<T: SomeTrait> mut Trait for Struct<T> { ... }

the only permitted override is one with an identical generic header:

override<T: SomeTrait> Trait for Struct<T> { ... }

Not override<T: AnotherTrait>, and not override Trait for Struct. Same parameter count, equivalent bounds. The override replaces a method across the whole family; super resolves at each monomorphization to the target family's instance for that T, which always exists and is unique because the headers match.

This restriction is deliberate: it is exactly what keeps the feature out of the constraint-solving and overlap-checking territory where specialization's soundness holes were found. Whether this restriction makes the feature too narrow to be worth it is a fair question — but if the restriction holds, the soundness argument does not need to solve specialization's problems.

I don't see a way to fix this feature that won't work for specialization.

I'd push back on the framing, because this proposal deliberately does not enter the territory where that question applies. It doesn't solve specialization's problem, and it doesn't claim to. The restriction described in my reply to the generic-parameter question (override headers must match the target) is what keeps it out of that territory.

The gap it fills is a different one: today, if a third-party crate has impl Parser for TheirType and one method is wrong, there is no type-system-level way to say "use their impl, replace this one method, keep the rest." Composition means forwarding every method by hand; newtype changes all call-site signatures; specialization, even if stable, expresses "more specific impl wins," not "same impl, one method replaced." The two mechanisms would coexist.

So the honest answer is: if "override headers must match the target" is acceptable, the soundness argument is straightforward and does not require advancing specialization. If the community judges that constraint too narrow to be worth the feature, that's a fair judgment — but it's a different discussion from "this has specialization's problems."

Indeed you were misunderstood. This does solve specialization's problems (barring matching the impl header which is possible but not entirely trivial). It also makes this useless IMO, because the only place I could see you wanting to change precisely this impl is in the same crate, where you can just change the original impl. The motivation section would benefit a lot from concrete cases (that is, really concrete; real-world examples) where this would help you and/or others.

Aside: I'm fairly sure you write your posts using AI. I'm not sure if it's against the rules here, but it is somewhat disrespectful.

2 Likes

It also makes this useless IMO, because the only place I could see you wanting to change precisely this impl is in the same crate, where you can just change the original impl.

I think there's a misunderstanding about rule 5. "Declaration-site resolution" only means a generic function's internal method calls don't change based on where it's instantiated — the same stability Rust already has. It does not limit where an override applies. An override in crate B can target impl mut in crate A (rule 7, orphan-rule exemption), and direct calls in crate B resolve to it.

So the premise "the only one who wants to change this impl owns it" doesn't hold. The case I have in mind is precisely a third-party impl I can't edit: fork, newtype-and-forward-everything, or wait for upstream are the current options.

The motivation section would benefit a lot from concrete cases.

Fair. I don't have a named real-world fork story to point to — this came out of design reasoning, not a specific incident. I'll rewrite Motivation with concrete scenarios and be explicit that they're illustrative, not case studies. If you have one in mind, I'd rather use yours.

Aside: I'm fairly sure you write your posts using AI.

Yes, the English text is drafted with AI assistance. The design and technical decisions are mine. I disclosed it at the bottom of the original post, but I take your point that disclosure doesn't make reading it less tedious. I'll keep it shorter and plainer going forward.

Thank you for your understanding.

The big thing you could do is cut down the amount of text - whichever AI is helping you (and I'm assuming here that you're using AI assistance because you can read English fluently, but struggle to write it) is producing verbose paragraphs that repeat the same concept multiple times in different ways without adding clarity.

This is crucial - for a big change like this, a real-world use case is essential. It's often the case that a restriction in the language forces better design of programs, and thus a "design reasoning" argument is unconvincing because we want to see how this improves things.

2 Likes

Someone else wrote a trait and a type system on it. I'm a consumer. I need to change one method of one impl in a crate I don't own. Today: newtype means wrapping the whole type and hand-forwarding every method; trait defaults only work if the author anticipated it; fork means maintaining a fork for one method; specialization expresses "more specific impl wins," not "same impl, one method replaced."

That gap is real even without a named incident. Whether it's frequent enough to justify a feature is a fair question, but the current workaround cost is concrete.

Given how rarely I need to write a newtype, and how it's almost always been because the underlying type implements traits I don't want implemented at all (such as Copy, or Add), I'd need to see compelling use cases for this feature in real Rust code, not invented examples, to make me think this is worth having.

Not only that, but for the use case you've described, I'd much prefer a way to make it easier to write newtypes - something that makes it easy to forward calls to an element of the newtype, not a way to have a type that behaves differently in different modules.

As a sketch (very much not thought through):

#[forward_impl_trait(res: (FromResidual))]
pub struct WeirdBrancher<T> { res: Result<T, T>, switch: bool }

impl<T> Try for WeirdBrancher<T> {
    #[forward_impl_trait(res: (Output, Residual, from_residual -> Self { res, switch: false} ))]

    fn branch(self)  -> ControlFlow<Self::Residual, Self::Output> {
        if switch {
            match res.branch() {
                ControlFlow::Continue(c) => ControlFlow::Break(c),
                ControlFlow::Break(b) => ControlFlow::Continue(b),
            }
        } else {
            res.branch()
        }
    }
}

#[forward_impl(res: (iter_left => iter, iter_right => iter_err, into_left => into_ok, into_right => into_err)]
impl<T> WeirdBrancher<T> {
    fn swap_branches(&mut self) { self.switch = !self.switch }
}

This is a very early sketch (so the syntax is rubbish) - but it tells you that WeirdBrancher forwards its entire FromResidual implementation to the field res, and within the implementation of Try, it forwards Output, Residual and from_residual to the field res (explaining how to construct Self from res::from_residual's return value), while implementing branch itself.

The advantage here is that I have complete control of which traits and methods are implemented by WeirdBrancher, just like a manual newtype, and I have a new name for my new type, so it's obvious to a reader of my code that this isn't your normal Result<T, T>.

On "a type that behaves differently in different modules": that's not what rule 5 does. An override doesn't change the type, and it doesn't change method resolution inside already-declared generic functions. It affects direct call sites in the crate that declares it. If that still reads as "different behavior in different modules" to you, I'd like to know which concrete case you mean, because that would be a real problem.

On the forwarding macro: we're on different axes, and they just happen to both be about method implementations. Your macro controls how a new type forwards methods to a field; the override proposal controls which methods of an existing impl get replaced without introducing a new type. In your case the new type is the point; in mine it's the cost.

They can coexist. A forwarding macro lets you build the newtype cheaply; impl mut + override lets you skip the newtype when it's too expensive. Nothing in one requires the other to change.

This still has a big pile of problems.

To start: you require overridable impls to be declared upfront. This is good, because overriding an arbitrary impl is unsound. Unfortunately, that means this feature has very little utility until stabilized. Worse, when should an impl be overridable? Not allowing overrides limits usefulness like the old orphan rules, but do allowing them means the impl can't be relied on for anything soundness-critical (it's worth noting this is quite similar to the situation with normal/unsafe traits today, but worse because it's about impls and not traits).

Another one: how deep does an overload propagate? If you have foo() with some override, that calls a giant tree of functions, do they all apply the override? If yes, that basically requires duplicating every function with an override and all of its transitive callees, creating a huge compile time and binary size penalty. If not, what are the precise rules? And how much utility do they have?

1 Like

you require overridable impls to be declared upfront... this feature has very little utility until stabilized.

Fair. The cold-start problem is real. But I'd separate it from soundness: impl mut isn't "anyone may override anything," it's "the author declares this is an extension point." That's a weaker contract than unsafe trait — no safety promise is involved, only an allowance. The adoption curve is closer to #[non_exhaustive] or #[must_use]: authors opt in when they see demand, and it's fine if most impls never do.

how deep does an overload propagate?

It doesn't propagate along the call chain. An override affects method resolution at direct call sites in the crate that declares it. If foo (in that crate) calls x.method(), it sees the override. If foo calls bar() declared elsewhere, bar's internal resolution is unchanged — it resolves at bar's declaration site, same as today.

So there's no duplication of transitive callees and no binary-size penalty of that kind. The cost is real utility: an override changes what you call directly, not what those callees call internally. That's a deliberate trade — it's what keeps the effect scoped and the resolution rule simple. Whether that trade leaves enough utility is a fair question, and I'd rather have it on those terms than on compile-time blowup that doesn't happen.

I don't understand. You're saying that I'm wrong to believe that, with the following code in a module (and assuming the necessary changes to std to match), Result in fn do_something has the behaviour given by the override, not the documented std behaviour?

override<T, E> IntoIterator for Result<T, E> {
    type Item = E;
    type IntoIter = std::option::IntoIter<E>;
    fn into_iter(self) -> std::option::IntoIter<E> { self.err().into_iter() }
}
// A thousand more lines of code here, so that if I'm looking at `do_something`,
// I don't see the `override` in scope.
fn do_something(…) {
    // more code here
    let res: Result<String, i32> = something_else(…);
    for r in res {
        // Here, because of the documentation of `Result`, I would expect `r: String`.
        // I thought, from your description, that I'd be surprised because the override makes it
        // `r: i32`
    }
}

This is the fundamental objection I have to this scheme - if I'm reading do_something in isolation, it is decidedly non-obvious that Result::into_iter(self) has been overriden, and that the override does something completely different to what I would normally expect.

In contrast, if it were trivial to have a newtype wrapper, I'd see a different type (not std::result::Result), and that would make it clear to me that I should expect different behaviour.

The AI voice is hugely annoying. If you can, please write yourself. If you cannot, how can I be sure the ideas are truly yours? This doesn't make me want to engage with this proposal.


Let's ignore the duplication problem that still exists, just on a smaller scale. What utility does this have, at all? If this only applies to direct local calls, you can just change the calls to other functions.

I encourage you once again to bring concrete, real-world motivating examples.

4 Likes