返回数组大小的关联const [重复]

问题描述 投票:1回答:1

考虑以下trait

pub trait Representable {
    const SIZE: usize;

    fn get(&self) -> [u8; SIZE];
    fn set(&mut self, value: [u8; SIZE]);
}

我想为任何可以表示为固定大小的字节数组的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

所以,好吧,现在我很困惑。我想不出的只是“但......但它就在那里”。我错过了什么?

rust
1个回答
3
投票

您可以使用关联类型实现几乎相同:

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!()
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.