gpt4 book ai didi

generics - 通用类型引用的 Rust 约束

转载 作者:行者123 更新时间:2023-11-29 07:47:46 26 4
gpt4 key购买 nike

场景如下:我有一个结构和特征对,如下所示:

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.
}
}

无论何时使用该操作都需要按值传递调用,并且问题与任何类似于“do_thing”的事情有关。我宁愿不必为 T 类型强制执行复制语义并想要一个解决方法。基本上我想知道以下内容:

  1. 是否可以对类型参数的引用强制执行特征约束?类似以下内容:struct Container<T: Sized + Operation> where &T: Operation { ... } .我试过稍微修改一下语法,但没有取得任何成功。
  2. 如果以上目前不可能,理论上可行吗?即它不违反任何要求的一致性属性或类似的内容?
  3. 是否可以创建第二个特征,比如 Middle: Operation , 其中Middle可以要求 Middle 的任何实现者, T , 还需要实现 Operation对于 &T .
  4. 如果以上两种情况都不可行,是否有其他一些常见的解决方法?

一些注意事项:

  • 我无权更改 Operation特质,它是给定的,这就是我要与之合作的东西。
  • 有一个 old RFC那谈到了对 where 子句的一些修改,但我没有找到与引用约束相关的任何内容。
  • 编译器版本:rustc 1.8.0 (db2939409 2016-04-11)

最佳答案

是的,您可以将&T 限制为Sized + Operation。您需要使用 Higher-Rank Trait Bounds在哪里

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());
}

打印

1

关于generics - 通用类型引用的 Rust 约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36759472/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com