Rust 是否可以声明一个表示特征的关联类型?

Rust 是否可以声明一个表示特征的关联类型?,rust,traits,associated-types,Rust,Traits,Associated Types,是否可以声明一个表示特征的关联类型?如果没有,我可以做些什么?尝试做: trait Foo { /// A trait representing all types that can be returned from baz() type ReturnType; fn baz(&self) -> Self::ReturnType; } 我遇到的最大问题是size特性,因为我需要一个函数,该函数返回实现ReturnType的类型的项向量: trait Foo

是否可以声明一个表示特征的关联类型?如果没有,我可以做些什么?尝试做:

trait Foo {
    /// A trait representing all types that can be returned from baz()
    type ReturnType;
    fn baz(&self) -> Self::ReturnType;
}
我遇到的最大问题是
size
特性,因为我需要一个函数,该函数返回实现
ReturnType
的类型的项向量:

trait Foo {
    type ReturnType;
    // option 1
    fn bar(&self) -> Vec<Self::ReturnType>;
    // option 2
    fn bar<T: Self::ReturnType>(&self) -> Vec<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()
        }
    }
}
///一个BufferedVec的实现
结构MyBufferedVec{
类型FromBuffer=MyFromTrait;
fn get(&self,索引:usize)->T{
::转换(self.data[index].as_ref())
}
}
性状MyFromTrait{
fn转换(val:选项)->Self;
}
i32的impl myfromtracit{
fn转换(val:选项)->i32{
匹配值{
一些(ref字节)=>字节[0]作为i32,
无=>0
}
}
}
字符串的impl myfromtracit{
fn转换(val:Option)->字符串{
匹配值{
一些(ref字节)=>String::from_utf8(字节),
无=>“”。到_字符串()
}
}
}

关联类型无法指定特征。你不能在Rust的任何地方指定特征。您可以要求泛型参数(或关联类型)需要实现特征

trait Foo {
    type ReturnType: Clone;
}
这样,
Foo
的任何实现者都需要确保他们选择的
ReturnType
也实现了
Clone

impl Foo for Bar {
    type ReturnType: i32;
}

正确的;我想你的用例是什么?Rust很有可能解决您的实际问题。一个MCVE显示使用您的trait和成员函数的代码将非常有帮助。我正在尝试构建一个API。基本上,我正在创建用户应该实现的特性,以符合我的API。问题是我想让其中一个函数返回一些实现用户定义的特征的东西,但是既然你无论如何都不能使用这个特征,既然你对它一无所知,你也可以允许用户传递任何类型。啊。。。泛型而不是关联类型。有道理。谢谢
impl Foo for Bar {
    type ReturnType: i32;
}