【发布时间】:2015-07-29 06:27:29
【问题描述】:
是否可以声明一个代表特征的关联类型?如果没有,我能做些什么呢?尝试做:
trait Foo {
/// A trait representing all types that can be returned from baz()
type ReturnType;
fn baz(&self) -> Self::ReturnType;
}
我遇到的最大问题是Sized 特征,因为我想要一个函数,它返回一个实现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 不会被调整大小,因为它是一个特征,选项 2 的问题是编译器不会将关联的类型识别为特征:failed to resolve. Use of undeclared type or module 'Self' 和 use of undeclared trait name 'Self::ReturnType' (这让我认为关联类型不能指定特征)
编辑:我正在尝试做的一个例子
/// 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()
}
}
}
【问题讨论】:
标签: rust traits associated-types