请考虑以下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
个字节。 / p>
但是,当我尝试编译时,会收到以下消息:
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
好吧,现在我很困惑。除了“但是……就在那儿”,我想到的不多。我想念什么?
答案 0 :(得分: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!()
}
}