考虑以下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
所以,好吧,现在我很困惑。我想不出的只是“但......但它就在那里”。我错过了什么?
您可以使用关联类型实现几乎相同:
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!()
}
}