Skip to content

Inconsistent behavior of borrow checker against method and function calls with &mut and &. #96417

Open
@jiangzhe

Description

@jiangzhe

I tried this code:

fn main() {
    let mut a = A{};
    
    // case 1: &mut and &mut
    // a.run(a.b1());                 // fail
    // A::run(&mut a, A::b1(&mut a)); // fail
    // run(&mut a, b1(&mut a));       // fail
    
    // case 2: &mut and &
    // a.run(a.b2());                 // ok
    // A::run(&mut a, A::b2(&a));     // fail
    // run(&mut a, b2(&a));           // fail

    // case 3: & and &mut
    // a.run2(a.b1());                // fail
    // A::run2(&a, A::b1(&mut a));    // fail
    // run2(&a, b1(&mut a));          // fail
}

fn run(a: &mut A, b: B) {}
fn run2(a: &A, b: B) {}

fn b1(a: &mut A) -> B { B{} }

fn b2(a: &A) -> B { B{} }

struct A {}

impl A {
    fn run(&mut self, b: B) {}
    
    fn run2(&self, b: B) {}
    
    fn b1(&mut self) -> B { B{} }
    
    fn b2(&self) -> B { B{} }
}

struct B {}

I expected to see this happen: all cases failed to compile.

Instead, this happened: Method call in case 2 succeeded, but function failed.

Meta

rustc --version --verbose:

rustc 1.59.0 (9d1b2106e 2022-02-23)
binary: rustc
commit-hash: 9d1b2106e23b1abd32fce1f17267604a5102f57a
commit-date: 2022-02-23
host: x86_64-unknown-linux-gnu
release: 1.59.0
LLVM version: 13.0.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-borrow-checkerArea: The borrow checkerC-discussionCategory: Discussion or questions that doesn't represent real issues.T-compilerRelevant to the compiler 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