Info
This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: Cannot imp block into a trait default using enum casting
Hi everyone,
I wanted to turn an impl funtion into a default function for a Trait. This seems not to work for enum as u8
#[repr(u8)]
pub enum SimpleEnum {
One,
Two,
}
impl SimpleEnum {
pub fn rank(self) -> u8 {
self as u8 + 1
}
}
fn main() {
let a = SimpleEnum::One;
assert_eq!(a.rank(), 1);
}
#[repr(u8)]
pub enum SimpleEnum {
One,
Two,
}
pub trait Simple
where
Self: Sized,
{
fn rank(self) -> u8 {
self as u8 + 1
}
}
impl Simple for SimpleEnum {}
fn main() {
let a = SimpleEnum::One;
assert_eq!(a.rank(), 1);
}
This gives me the following error:
error[E0605]: non-primitive cast: `Self` as `u8`
--> src/main.rs:11:9
|
11 | self as u8 + 1
| ^^^^^^^^^^ an `as` expression can only be used to convert between primitive types or to coerce to a specific trait object
For more information about this error, try `rustc --explain E0605`.
error: could not compile `enumtrait` (bin "enumtrait") due to 1 previous error
I looked at the rustc --explain E0605
and the reference guide, but that did not help me to understand why the impl fn accepts self as u8 + 1, but the Trait not.
I am relatively new to Rust. So I probably didn't quite understand the things that I red.
Is there anyone who can explain the error message in simple terms and why it works in the implfn and not in the Trait definition?
Thanx in advance.
3 posts - 3 participants
🏷️ Rust_feed