Skip to content

Weird error message when trying to use a private constructor in a method #143008

@gammelalf

Description

@gammelalf

I tried this code:

pub struct MyStruct {}

mod submodule {
    use super::MyStruct;
    
    pub struct MyRef<'a>(&'a MyStruct); // <- Private field; private constructor
}

use self::submodule::MyRef;

impl MyStruct {
    pub fn method(&self) -> MyRef {
        MyRef(self) // <- Invalid use of private constructor
    }
}

pub fn function(my_struct: &MyStruct) -> MyRef {
    MyRef(my_struct) // <- Invalid use of private constructor
}

method and function contain the same error.
The constructor of MyRef is private because its field is private.

I expected to see this happen:
In bothmethod and function I expected to see the same error message:
"cannot initialize a tuple struct which contains private fields"

Instead, this happened:
The 2nd error (in function) is what I expected.
However, the 1st error (in method) is completely nonsensical (at least to me).

error[E0423]: expected function, tuple struct or tuple variant, found struct `MyRef`
  --> src/lib.rs:13:9
   |
13 |         MyRef(self) // <- Invalid use of private constructor
   |         ^^^^^------
   |         |
   |         help: try calling `MyRef` as a method: `self.MyRef()`

error[E0423]: cannot initialize a tuple struct which contains private fields
  --> src/lib.rs:18:5
   |
18 |     MyRef(my_struct) // <- Invalid use of private constructor
   |     ^^^^^
   |
note: constructor is not visible here due to private fields
  --> src/lib.rs:6:26
   |
6  |     pub struct MyRef<'a>(&'a MyStruct); // <- Private field; private constructor
   |                          ^^^^^^^^^^^^ private field
help: consider making the field publicly accessible
   |
6  |     pub struct MyRef<'a>(pub &'a MyStruct); // <- Private field; private constructor
   |                          +++

Meta

I tried the current stable (1.87.0) compiler on the rust playground.

Metadata

Metadata

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsC-bugCategory: This is a bug.D-incorrectDiagnostics: A diagnostic that is giving misleading or incorrect information.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