Description
Code
struct Foo {
a: Fn(),
b: Fn(),
}
Current output
error[E0277]: the size for values of type `(dyn Fn() + 'static)` cannot be known at compilation time
--> src/lib.rs:2:8
|
2 | a: Fn(),
| ^^^^ doesn't have a size known at compile-time
|
= help: the trait `Sized` is not implemented for `(dyn Fn() + 'static)`
= note: only the last field of a struct may have a dynamically sized type
= help: change the field's type to have a statically known size
help: borrowed types always have a statically known size
|
2 | a: &Fn(),
| +
help: the `Box` type always has a statically known size and allocates its contents in the heap
|
2 | a: Box<Fn()>,
| ++++ +
error[E0782]: trait objects must include the `dyn` keyword
--> src/lib.rs:2:8
|
2 | a: Fn(),
| ^^^^
|
help: add `dyn` keyword before this trait
|
2 | a: dyn Fn(),
| +++
error[E0782]: trait objects must include the `dyn` keyword
--> src/lib.rs:3:8
|
3 | b: Fn(),
| ^^^^
|
help: add `dyn` keyword before this trait
|
3 | b: dyn Fn(),
| +++
Desired output
There are two fixes that I think would be wise here.
-
Most importantly, the E0277 should not occur; the compiler should not
attempt to continue interpreting the program as if it were in edition 2015. Or, at a minimum, the E0782 should appear first. -
E0782 could be better expressed, in the modern perspective, as “expected type, found trait”. Don't bring up trait objects at all until the author writes
dyn
.
Rationale and extra context
Today, when a newcomer writes a trait in a type position, it most often means they're confused about what the difference is, not that they wanted a trait object and need to be taught the new syntax. The whole point of adding dyn
to Rust's syntax was to remove that easy confusion. Therefore, the compiler should stop making the assumption whatsoever that the author of the code meant a trait object.
This will have the further advantage that newcomers will not be confronted with errors about Sized
when they probably didn't even mean to use any DST.
Rust Version
rustc 1.81.0-nightly (ba1d7f4a0 2024-06-29)
binary: rustc
commit-hash: ba1d7f4a083e6402679105115ded645512a7aea8
commit-date: 2024-06-29
host: x86_64-apple-darwin
release: 1.81.0-nightly
LLVM version: 18.1.7