rust-lang / rust-lang/rust

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

Open
#143,008 1 comment 0 reactions 1 assignee View on GitHub

@compiler-errors is already working on this.

Since Jun 26, 2025.

A-diagnostics C-bug T-compiler
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

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.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.