Description
Summary: Enabling the const_generics
feature makes an object safe trait with const generics unsafe.
The following code compiles successfully as expected (note the angle brackets around 42):
trait TraitWithConstGeneric<const GENERIC: u64> {}
trait ObjectSafeTrait: TraitWithConstGeneric<{42}> {}
// Check that `ObjectSafeTrait` is in fact object safe
type __ = dyn ObjectSafeTrait;
However, when I enable the const_generics
feature, compilation fails (note the angle brackets around 42):
#![feature(const_generics)]
trait TraitWithConstGeneric<const GENERIC: u64> {}
trait ObjectSafeTrait: TraitWithConstGeneric<{42}> {}
// Check that `ObjectSafeTrait` is in fact object safe
type __ = dyn ObjectSafeTrait;
with the error that "ObjectSafeTrait
cannot be made into an object".
Full Error Message
error[E0038]: the trait `ObjectSafeTrait` cannot be made into an object
--> src/lib.rs:7:11
|
7 | type __ = dyn ObjectSafeTrait;
| ^^^^^^^^^^^^^^^^^^^ `ObjectSafeTrait` cannot be made into an object
|
note: for a trait to be "object safe" it needs to allow building a vtable to allow the call to be resolvable dynamically; for more information visit <https://doc.rust-lang.org/reference/items/traits.html#object-safety>
--> src/lib.rs:4:24
|
4 | trait ObjectSafeTrait: TraitWithConstGeneric<{42}> {}
| --------------- ^^^^^^^^^^^^^^^^^^^^^^^^^^^ ...because it uses `Self` as a type parameter
| |
| this trait cannot be made into an object...
For more information about this error, try `rustc --explain E0038`.
You can also reproduce the behaviour on the playground:
https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=e083b7b2d1cb62e355201987e6076775
The same error can also be reproduced on stable 1.53.0, though rustc then also complains about the feature, of course.
It is also worth noting that when the angle brackets around 42 are removed, i.e. TraitWithConstGeneric<42>
, the code compiles both with and without the const_generics
feature.
Meta
rustc --version --verbose
:
rustc 1.56.0-nightly (2faabf579 2021-07-27)
binary: rustc
commit-hash: 2faabf579323f5252329264cc53ba9ff803429a3
commit-date: 2021-07-27
host: x86_64-unknown-linux-gnu
release: 1.56.0-nightly
LLVM version: 12.0.1