特征内的常量表达式?

2024-04-19

我有一个特点,看起来像这样:

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

不过我想做这样的事情:

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

它给了我这个错误():

   |
   |     fn to_buf(&self) -> [u8; Self::N];
   |                              ^^^^^^^ cannot perform const operation using `Self`
   |
   = note: type parameters may not be used in const expressions
   = help: use `#![feature(generic_const_exprs)]` to allow generic const expressions

是否可以?


经过一番研究,我发现,在 nightly 中,Rust 允许我们使用泛型 const 表达式,在此 (#![feature(generic_const_exprs)]) 特征标志,

然而,这还远未达到稳定。

#![allow(warnings)]
#![feature(generic_const_exprs)]

trait Buf {
    const N: usize;
    fn to_buf(&self) -> [u8; Self::N];
    fn from_buf(buf: [u8; Self::N]) -> Self;
}
macro_rules! impl_trait {
    ($name:ident for $($t:ty:$N:literal)*) => ($(
        impl $name for $t {
            const N: usize = $N;
            fn to_buf(&self) -> [u8; $N] {
                self.to_le_bytes()
            }
            fn from_buf(bytes: [u8; $N]) -> Self {
                Self::from_le_bytes(bytes)
            }
        }
    )*)
}
impl_trait!(Buf for u8:1 u16:2 u32:4 i8:1 i16:2 i32:4);

fn test<T: Buf>(buf: T, rhs: [u8; T::N])
where
    [u8; T::N]:,
{
    assert_eq!(buf.to_buf(), rhs);
}

fn main() {
    test(123_u8,  [123]);
    test(123_u16, [123, 0]);
    test(123_u32, [123, 0, 0, 0]);

    test(-123i8,  [133]);
    test(-123i16, [133, 255]);
    test(-123i32, [133, 255, 255, 255]);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

特征内的常量表达式? 的相关文章

随机推荐