是否可能声明一个关联类型来代表一个特性?如果不行,我该怎么办?尝试做:
trait Foo {
/// A trait representing all types that can be returned from baz()
type ReturnType;
fn baz(&self) -> Self::ReturnType;
}
我遇到的最大问题是关于 Sized
trait,因为我想要一个返回实现了 ReturnType
的类型的向量的函数:
trait Foo {
type ReturnType;
// option 1
fn bar(&self) -> Vec<Self::ReturnType>;
// option 2
fn bar<T: Self::ReturnType>(&self) -> Vec<T>;
}
选项1存在的问题是
ReturnType
无法确定大小,因为它是一个 trait,而选项2存在的问题是编译器无法将关联类型识别为 trait:failed to resolve. Use of undeclared type or module 'Self'
和 use of undeclared trait name 'Self::ReturnType'
(这让我想到了关联类型不能指定 traits)。编辑:以下是我尝试做的示例。
/// Represents all types that store byte-data instead of the actual
/// element
trait BufferedVec {
/// the trait representing types that can be converted from the byte-data
type FromBuffer;
/// return the data at the given index, converted into a given type
fn get<T: Self::FromBuffer>(&self, index: usize) -> T;
}
用户的实现可能是:
/// An implementation of a BufferedVec
struct MyBufferedVec<'a> {
data: &'a [Option<Vec<u8>>]
}
impl<'a> BufferedVec for MyBufferedVec<'a> {
type FromBuffer = MyFromTrait;
fn get<T: MyFromTrait>(&self, index: usize) -> T {
<T as MyFromTrait>::convert(self.data[index].as_ref())
}
}
trait MyFromTrait {
fn convert(val: Option<&[u8]>) -> Self;
}
impl MyFromTrait for i32 {
fn convert(val: Option<&[u8]>) -> i32 {
match val {
Some(ref bytes) => bytes[0] as i32,
None => 0
}
}
}
impl MyFromTrait for String {
fn convert(val: Option<&[u8]>) -> String {
match val {
Some(ref bytes) => String::from_utf8(bytes),
None => "".to_string()
}
}
}