Skip to content

Adding impl Add<char> for String breaks code (adding an impl leads to breakage due to deref coercions) #51916

Open
@LukasKalbertodt

Description

@LukasKalbertodt

I just prepared a PR to fix #38784. I wanted to add Add<char> and AddAssign<char> impls for String. However, this breaks the following code:

let a = String::from("a");
let b = String::from("b");
a + &b;

(Playground)

Apparently, without Add<char>, deref coercion is used to turn &String into &str. With the additional impl, deref coercion is no more and thus it results in:

error[E0277]: cannot add `&std::string::String` to `std::string::String`
[...]
     = help: the trait `std::ops::Add<&std::string::String>` is not implemented for `std::string::String`

This is unexpected, because RFC 1105 says that adding an implementing for a non-fundamental trait is a minor change and thus should not require a major version bump. But if I were to submit a PR which adds Add<char> for String, it would probably not be merged, because it breaks a bunch of crates. a + &b for a and b being String is widely used.

I would have expected that either deref coercion wouldn't happen in cases where it influences the trait selection (in order to avoid this breakage) or that deref coercion would still happen if there is more than one impl. Since the former is not possible anymore, I think the latter is the solution to this problem.

The third option (I can see) would be to change RFC 1105 and amend a section about this special case.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-coercionsArea: implicit and explicit `expr as Type` coercionsA-inferenceArea: Type inferenceA-trait-systemArea: Trait systemC-bugCategory: This is a bug.T-langRelevant to the language team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions