Const expressions inside trait?

I have a trait that look like this:

pub trait Buf<const N: usize> {
    fn to_buf(&self) -> [u8; N];
    fn from_buf(buf: [u8; N]) -> Self;
}

However I want to do something like this:

trait Buf {
    const N: usize;
    fn to_buf(&self) -> [u8; Self::N];
    fn from_buf(buf: [u8; Self::N]) -> Self;
}

Any hack, trick? Is it possible?

For your curiosity, I described my use cases for this in stack overflow

This compiles on nightly Rust if you enable #![feature(generic_const_exprs)]. However, it appears there's still quite a bit of work to do before that feature can be stabilized.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.