Fun with Rust: Never implemented traits

I was having fun with traits in Rust and discovered, that you can create traits that cannot be implemented.

pub trait Never {
    fn uncallable() {
        println!("I can never be called.");
    }

    fn never_implemented();
}

impl<T> Never for T
where
    T: Never,
{
    fn never_implemented() {
        println!("I am never implemented and thus cannot be called.");
    }
}

pub fn test(never: impl Never) {
    println!("Can't call me!");
}

fn main() {
    Never::uncallable();
}

Errors:

   Compiling playground v0.0.1 (/playground)
error[E0790]: cannot call associated function on trait without specifying the corresponding `impl` type
  --> src/main.rs:20:5
   |
2  | /     fn uncallable() {
3  | |         println!("I can never be called.");
4  | |     }
   | |_____- `Never::uncallable` defined here
...
20 |       Never::uncallable();
   |       ^^^^^^^^^^^^^^^^^^^ cannot call associated function of trait

warning: unused variable: `never`
  --> src/main.rs:15:13
   |
15 | pub fn test(never: impl Never) {
   |             ^^^^^ help: if this is intentional, prefix it with an underscore: `_never`
   |
   = note: `#[warn(unused_variables)]` on by default

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

I did this just for fun and to play with the language, but it made me wonder, whether there's an actual application for traits that are never implemented....?

1 Like
-impl<T> Never for T
+impl<T: ?Sized> Never for T

:slightly_smiling_face:

And even then... there are some weird corner cases.

I don't know if this would count, but I can see allowing such code as it might be the output of a macro or such. I.e. disallowing it now it breaking.[1]

There's definitely an argument for allowing trivially unsatisfiable bounds in other cases.[2]

There's definitely a use for preventing additional implementations.[3]


  1. Infallibly proving that a trait isn't implementable is probably undecidable anyway. Fallibly trying is a waste of compiler time. ↩︎

  2. Also related. ↩︎

  3. Also related. ↩︎

5 Likes

Hmm... coinduction for all traits may change your "can't implement for anything" into an "implemented for everything".

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.