我怎样才能使这样的东西工作:
struct FooStruct<A, B> where A : B, B : ?Sized {...}
我搜索了一些类型标记来告诉编译器 S
必须是一个特征,搜索了 Rust 文档以寻找这种模式的一些例子,但找不到其他人有同样的问题。这是我的代码:
trait Factory<S> where S : ?Sized {
fn create(&mut self) -> Rc<S>;
}
trait Singleton<T> {
fn create() -> T;
}
struct SingletonFactory<T> {
instance: Option<Rc<T>>
}
impl<S, T> Factory<S> for SingletonFactory<T> where S : ?Sized, T : S + Singleton<T> {
fn create(&mut self) -> Rc<S> {
if let Some(ref instance_rc) = self.instance {
return instance_rc.clone();
}
let new_instance = Rc::new(T::create());
self.instance = Some(new_instance.clone());
new_instance
}
}
编译失败并出现以下错误:
--> src/lib.rs:15:57
|
15 | impl<S, T> Factory<S> for SingletonFactory<T> where T : S + Singleton<T> {
| ^ not a trait
最佳答案
我设法找到了答案: std::marker::Unsize<T>
trait ,尽管在当前版本的 Rust (1.14.0) 中不是稳定的功能。
pub trait Unsize<T> where T: ?Sized { }
Types that can be "unsized" to a dynamically-sized type.
这比“实现”语义更广泛,但它是我应该从一开始就搜索的内容,因为示例代码中的通用参数可以是结构和特征或两个特征之外的其他东西(比如大小和未大小的数组)。
问题中的通用示例可以写成:
struct FooStruct<A, B>
where A: Unsize<B>,
B: ?Sized,
{
// ...
}
还有我的代码:
impl<S, T> Factory<S> for SingletonFactory<T>
where S: ?Sized,
T: Unsize<S> + Singleton<T>,
{
// ...
}
关于generics - 如何在 Rust 中添加一个泛型类型实现另一个泛型类型的约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41664723/