Skip to content

Calling nonexistent function on a trait causes spurious object safety errors #58734

Closed
@SNCPlay42

Description

@SNCPlay42
trait Trait {
    fn exists(self) -> ();
    
    fn not_object_safe() -> Self;
}

impl Trait for () {
    fn exists(self) -> () {
    }
    
    fn not_object_safe() -> Self {
        ()
    }
}

fn main() {
    // object-safe or not, this call is OK
    Trait::exists(());
    // but, in addition to nonexistence, this causes an object safety error
    Trait::nonexistent(());
}

Gives

error[E0599]: no function or associated item named `nonexistent` found for type `dyn Trait` in the current scope
  --> src/main.rs:20:5
   |
20 |     Trait::nonexistent(());
   |     ^^^^^^^^^^^^^^^^^^ function or associated item not found in `dyn Trait`

error[E0038]: the trait `Trait` cannot be made into an object
  --> src/main.rs:20:5
   |
20 |     Trait::nonexistent(());
   |     ^^^^^^^^^^^^^^^^^^ the trait `Trait` cannot be made into an object
   |
   = note: method `not_object_safe` has no receiver

error: aborting due to 2 previous errors

As the first call shows, it is in fact possible to call a non-object-safe trait's methods in this manner, but calling a nonexistent method gives an object safety error, adding noise to the output.

Note as well the E0599 error says the receiver type is dyn Trait.

Playground

Metadata

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lints

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions