#const generics in traits

3 messages · Page 1 of 1 (latest)

tepid gulch
#

In the code below I have the function gen_regs which returns a [Register<T>; N] . In the fmt_gen_regs function I want to call gen_regs then iterate over the array however I get an error from the compiler:

type annotations needed
cannot satisfy `_: Debug`rustcE0283
arch.rs(20, 36): required by a bound in `Arch::gen_regs`
arch.rs(33, 31): consider specifying the generic arguments: `::<N, T>`
arch.rs(33, 31): consider specifying the type arguments in the function call: `::<N, T>`

Is there a way to fix this?

pub trait Arch {
    type Usize: Debug + Copy + Unsigned;

    fn pc(&self) -> Register<Self::Usize>;
    fn sp(&self) -> Register<Self::Usize>;
    fn gen_regs<const N: usize, T: Debug + Copy + Clone + Unsigned>(&self) -> [Register<T>; N];

    fn fmt_pc(&self, xterm_color: Option<XtermColors>) -> String {
        fmt_reg!(self.pc().name, self.pc().fmt_val, xterm_color)
    }

    fn fmt_sp(&self, xterm_color: Option<XtermColors>) -> String {
        fmt_reg!(self.sp().name, self.sp().fmt_val, xterm_color)
    }

    fn fmt_gen_regs(&self, xterm_color: Option<XtermColors>) -> String {
        let mut s = String::new();

        for r in self.gen_regs() {
            s.push_str(&fmt_reg!(r.name, r.fmt_val, xterm_color))
        }

        s
    }
}

#[derive(Copy, Clone)]
pub struct Register<T: Debug + Copy + Clone + Unsigned> {
    name: &'static str,
    fmt_val: &'static str,
    _type: PhantomData<T>,
}

vocal plover
#

gen_regs returns an array of T with length N. Nothing in your code specifies what T and N are.

#

You use T in a way that needs it to be Debug (hence the _: Debug error message), and you just leave N entirely unspecified.