Skip to content

Private field can cause confusion with identically named field on a deref target #149546

@yara-blue

Description

@yara-blue

Code

mod structs {
    pub struct A {
        // this is the field we want but can't get as it's not pub
        field: usize,
        b: B,
    }
    
    pub struct B {
        // this field is unfortunately named the same but is pub
        pub field: bool,
    }
    
    impl std::ops::Deref for A {
        type Target = B;
    
        fn deref(&self) -> &Self::Target {
            &self.b
        }
    }
}

use structs::A;
fn try_to_use_field_in_a(a: A) {
    // getting: cannot add {integer} to bool 
    // would ideally be informed A::field is not public
    a.field + 5;   
}

fn main() {}

Current output

error[E0369]: cannot add `{integer}` to `bool`
  --> src/main.rs:26:13
   |
26 |     a.field + 5;   
   |     ------- ^ - {integer}
   |     |
   |     bool

For more information about this error, try `rustc --explain E0369`.
error: could not compile `playground` (bin "playground") due to 1 previous error

Desired output

error[E0369]: cannot add `{integer}` to `bool`
  --> src/main.rs:26:13
   |
26 |     a.field + 5;   
   |     ------- ^ - {integer}
   |     |
   |     bool 
help: there is an identically named field on A we ignore since it's not public


or even:

error[E0616]: field `field` of struct `A` is private
  --> src/main.rs:26:7
   |
26 |     a.field + 5;   
   |       ^^^^^ private field
help: there is a identically named field on B and A derefs into B however this field has a different type

Rationale and extra context

No response

Other cases

Rust Version

rustc 1.91.1 (ed61e7d7e 2025-11-07)
binary: rustc
commit-hash: ed61e7d7e242494fb7057f2657300d9e77bb4fcb
commit-date: 2025-11-07
host: x86_64-unknown-linux-gnu
release: 1.91.1
LLVM version: 21.1.2

Anything else?

Happy to work on this over Christmas.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-visibilityArea: Visibility / privacyD-confusingDiagnostics: Confusing error or lint that should be reworked.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