Need help understanding which type constraints to use for num_enum

PressRex profile image
by PressRex
Need help understanding which type constraints to use for num_enum

Hello,
I am fairly new to Rust and I am trying to convert a snippet of Rust code into a version that's up to date with the current crate version, as well as change it slightly to operate on the self instead of defining a new free function

Here's a link to the code

#[derive(Debug, Copy, Clone, FromPrimitive)]
enum Direction {
    NORTH = 0,
    SOUTH,
    EAST,
    WEST,
}

fn turn(d: Direction) -> Direction {
    match FromPrimitive::from_u8(d as u8 + 1) {
        Some(d2) => d2,
        None => FromPrimitive::from_u8(0).unwrap(),
    }
}

I figured out how to update the exact function with crate num_enum version 0.7.3

use num_enum::{FromPrimitive, TryFromPrimitive};

//#[derive(Debug, Copy, Clone, FromPrimitive)]
#[derive(Debug, Default, Copy, Clone, TryFromPrimitive)]
#[repr(u8)]
enum Direction {
    #[default]
    NORTH = 0,
    SOUTH,
    EAST,
    WEST,
}

fn turn(d: Direction) -> Direction {
    match TryFromPrimitive::try_from_primitive(d as u8 + 1) {
        Ok(res) => res,
        Err(_) => Direction::default(),
    }
}

But I'm having some trouble with defining it on the self instead. Here's what I've tried so far:

//impl<T> Direction where T: From<Direction> + Add<u8> {
impl<T: Add<u8>> Direction where T: From<Direction>  {
    fn next(self) -> Self {
        //let test = <Direction as Into<T>>::into(self) + 1u8;
        let test = <Direction as Into<T>>::into(self);
        //let test = self.into() + 1u8;
        self
    }
}

I added the T type param when rustc suggested let test = <Direction as Into<T>>::into(self); when I tried to do let test = self.into() + 1u8;. Of course, I don't expect rustc to give a suggestion for each step. Specifically, I'm confused about the error: the type parameter T is not constrained by the impl trait, self type, or predicates as I thought that the Add<u8> on that line would constrain it.

Source: View source

PressRex profile image
by PressRex

Subscribe to New Posts

Lorem ultrices malesuada sapien amet pulvinar quis. Feugiat etiam ullamcorper pharetra vitae nibh enim vel.

Success! Now Check Your Email

To complete Subscribe, click the confirmation link in your inbox. If it doesn’t arrive within 3 minutes, check your spam folder.

Ok, Thanks

Read More