Skip to content

Can't return &mut str ("values differ in mutability") from a method when implementing a trait for str #17361

Closed
@japaric

Description

@japaric

STR

trait Trait for Sized? {
    fn method(&mut Self) -> &mut Self;
}

impl<T> Trait for [T] {
    // This works
    fn method(s: &mut [T]) -> &mut [T] {
        s
    }
}

impl Trait for str {
    // This doesn't work
    fn method(s: &mut str) -> &mut str {
        s
    }
}

// But this works
fn function(s: &mut str) -> &mut str {
    s
}

fn main() {}

Output

str.rs:14:5: 16:6 error: method `method` has an incompatible type for trait: values differ in mutability [E0053]
str.rs:14     fn method(s: &mut str) -> &mut str {
str.rs:15         s
str.rs:16     }
error: aborting due to previous error

Version

rustc 0.12.0-pre (9508faa22 2014-09-17 23:45:36 +0000)

The compiler complains that &mut str and &mut Self where Self = str differ in mutability, but that looks like a bug to me.

As a side note, I found this issue while trying to implement the Borrow trait for str as proposed by the Collections reform RFC.

cc @nick29581

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-DSTsArea: Dynamically-sized types (DSTs)

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions