CSa*_*San 6 generics reference constraints rust
这是场景:我有一个结构和特征对,如下所示:
trait Operation {
fn operation(self) -> u32
}
struct Container<T: Sized + Operation> {
x:T
}
impl <T: Sized + Operation> for Container<T> {
fn do_thing(&self) -> u32 {
// Do something with the field x.
}
}
Run Code Online (Sandbox Code Playgroud)
无论何时使用,该操作都需要按值传递,并且问题与"do_thing"类似.我宁愿不必为该类型强制执行复制语义,T并希望为此解决此问题.基本上我想知道以下内容:
struct Container<T: Sized + Operation> where &T: Operation { ... }.我尝试了一下语法,但我没有取得任何成功.Middle: Operation,在那里Middle可以要求任何实施者Middle,T,也需要实现Operation的&T.一些说明:
Operation特性,它是给定的,这就是我要使用的东西.是的,你可以限制&T为Sized + Operation.你需要使用更高等级的特质界限和where.
trait Operation {
fn operation(self) -> u32;
}
struct Container<T>
where for<'a> &'a T: Sized + Operation
{
x: T,
}
impl<T> Container<T>
where for<'a> &'a T: Sized + Operation
{
fn do_thing(&self) -> u32 {
self.x.operation()
}
}
impl<'a> Operation for &'a u32 {
fn operation(self) -> u32 {
*self
}
}
fn main() {
let container = Container { x: 1 };
println!("{}", container.do_thing());
}
Run Code Online (Sandbox Code Playgroud)
版画
1
Run Code Online (Sandbox Code Playgroud)