Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Weird mutability issue when calling extension methods on a mutable reference to a Sized? generic #22888

Closed
sfackler opened this issue Feb 28, 2015 · 3 comments
Labels
A-typesystem Area: The type system

Comments

@sfackler
Copy link
Member

use std::io::prelude::*;

trait Foo: Write {
    fn foo(&mut self) {}
}

impl<W: Write> Foo for W {}

fn foo<W: Write+?Sized>(w: &mut W) {
    w.foo();
}

fn main() {
    foo(&mut std::io::sink());
}
test.rs:10:5: 10:6 error: cannot borrow immutable local variable `w` as mutable
test.rs:10     w.foo();
               ^
error: aborting due to previous error

Dropping the ?Sized bound or calling flush instead of foo makes it compile just fine.

@sfackler sfackler added the A-typesystem Area: The type system label Feb 28, 2015
@Stebalien
Copy link
Contributor

Also, changing the function signature to 'mut w: &mut W' fixes this.

use std::io::prelude::*;

trait Foo: Write {
    fn foo(&mut self) {}
}

impl<W: Write> Foo for W {}

fn foo<W: Write+?Sized>(/* HERE */ mut w: &mut W) {
    w.foo();
}

fn main() {
    foo(&mut std::io::sink());
}

@Stebalien
Copy link
Contributor

Triage: no change.

@Mark-Simulacrum
Copy link
Member

I think this is technically correct, though an oddity. &mut W as Foo means that self in Foo will be &mut W, which will then mean that in order to call foo, you need to pass &mut &mut W, and in order to make that work, you'd need to have w be mutable. I think this is because W is ?Sized, which means that it technically doesn't implement Foo itself, i.e., impl<W: Write> Foo for W {} isn't matching on it. That matches for &mut w, though, since Write is implemented for &mut T where T: Write.

I'm going to close per the above, but please reopen if I'm wrong.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-typesystem Area: The type system
Projects
None yet
Development

No branches or pull requests

3 participants