如何在 Rust 中添加一个泛型类型实现另一个泛型类型的约束?
How to add constraint that one generic type implements another generic type in Rust?
我怎样才能做出这样的作品:
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>,
{
// ...
}
我怎样才能做出这样的作品:
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>,
{
// ...
}