返回数组大小的关联常量

Mat*_*nti 2 rust

考虑以下trait

pub trait Representable {
    const SIZE: usize;

    fn get(&self) -> [u8; SIZE];
    fn set(&mut self, value: [u8; SIZE]);
}
Run Code Online (Sandbox Code Playgroud)

我想为任何struct可以表示为固定大小的字节数组的对象实现它。为此,我添加了trait一个关联常量SIZE,使得返回get和接受的表示形式为set字节SIZE长。

但是,当我尝试编译时,我收到以下消息:

error[E0425]: cannot find value `SIZE` in this scope
 --> src/bytewise/representable.rs:4:27
  |
4 |     fn get(&self) -> [u8; SIZE];
  |                           ^^^^ not found in this scope

error[E0425]: cannot find value `SIZE` in this scope
 --> src/bytewise/representable.rs:5:35
  |
5 |     fn set(&mut self, value: [u8; SIZE]);
  |                                   ^^^^ not found in this scope
Run Code Online (Sandbox Code Playgroud)

所以,好吧,现在我很困惑。我除了“但是……但是它就在那里”之外想不出更多的东西。我缺少什么?

Sve*_*rev 6

您可以通过使用关联类型来实现几乎相同的效果:

pub trait Representable {
    type T;

    fn get(&self) -> Self::T;
    fn set(&mut self, value: Self::T);
}

pub struct ReprA;
impl Representable for ReprA{
    type T = [u8; 10];

    fn get(&self) -> Self::T{
        unimplemented!()
    }

    fn set(&mut self, value: Self::T){
        unimplemented!()
    }
}

pub struct ReprB;
impl Representable for ReprB{
    type T = [u8; 50];

    fn get(&self) -> Self::T{
        unimplemented!()
    }

    fn set(&mut self, value: Self::T){
        unimplemented!()
    }
}
Run Code Online (Sandbox Code Playgroud)