性格特征中的常量表达? [英] Const expressions inside trait?
本文介绍了性格特征中的常量表达?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个如下所示的特征:
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;
}
它显示以下错误(playground):
|
| 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
可以吗?
Rust
经过研究发现,在夜间,推荐答案允许我们使用泛型常量表达式,在这个(#![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]);
}
这篇关于性格特征中的常量表达?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文