有没有可能声明一个关联类型来代表一个特质?

3

是否可能声明一个关联类型来代表一个特性?如果不行,我该怎么办?尝试做:

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()
        }
    }
}
1个回答

2

关联类型不能指定trait。在Rust中,你无法指定任何trait。但可以要求一个泛型参数(或关联类型)需要实现一个trait。

trait Foo {
    type ReturnType: Clone;
}

这样,任何实现 Foo 的人都需要确保他们选择的 ReturnType 也实现了 Clone
impl Foo for Bar {
    type ReturnType: i32;
}

好的,我也想到了。 - brandonchinn178
你的使用情况是什么?Rust很有可能有一个解决你实际问题的方案。一个显示使用你的特性和成员函数的代码示例会非常有帮助。 - oli_obk
1
但是既然您无法使用该特性,因为您对它一无所知,那么您可以允许用户传递任何类型。 - oli_obk
啊...使用泛型而不是关联类型。很有道理。谢谢! - brandonchinn178
您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - oli_obk
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接