是否可以声明一个表示特征的关联类型?如果没有,我该怎么办?尝试做:
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 的问题是编译器不会将关联类型识别为特征:未能解决。使用未声明的类型或模块“Self”
和使用未声明的特征名称“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 的任何地方指定特征。您可以要求泛型参数(或关联类型)需要实现特征。
trait Foo {
type ReturnType: Clone;
}
这样,Foo
的任何实现者都需要确保他们选择的 ReturnType
也实现了 Clone
。
impl Foo for Bar {
type ReturnType: i32;
}
关于rust - 是否可以声明一个表示特征的关联类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31692770/