gpt4 book ai didi

rust - 如何解决 HRTB 错误?

转载 作者:行者123 更新时间:2023-11-29 08:13:55 27 4
gpt4 key购买 nike

由于 compiler bug,此代码段无法编译:

struct Theory<'a, T: 'a> {
left: &'a T,
}

pub struct Contain<'a, T: 'a, U>
where
&'a T: IntoIterator,
for<'x> <(&'a T) as IntoIterator>::Item: PartialEq<&'x U>,
{
theory: Theory<'a, T>,
right: U,
}

impl<'a, T: 'a, U> Drop for Contain<'a, T, U>
where
&'a T: IntoIterator,
for<'x> <(&'a T) as IntoIterator>::Item: PartialEq<&'x U>,
{
fn drop(&mut self) {
//TODO
}
}

fn main() {}

我需要这个,因为我必须将迭代器 ItemU 进行比较;但是 Item 是引用类型,因为我在借用的集合中调用了 into_iter()

然后我尝试了类似这样的方法来解决:

struct Theory<'a, T: 'a> {
left: &'a T,
}

pub struct Contain<'a, 'b: 'a, T: 'a, U: 'b>
where
&'a T: IntoIterator,
<(&'a T) as IntoIterator>::Item: PartialEq<&'b U>,
{
theory: Theory<'a, T>,
right: U,
_marker: ::std::marker::PhantomData<&'b ()>,
}

impl<'a, 'b, T: 'a, U> Drop for Contain<'a, 'b, T, U>
where
&'a T: IntoIterator,
<(&'a T) as IntoIterator>::Item: PartialEq<&'b U>,
{
fn drop(&mut self) {
for left in self.theory.left.into_iter() {
if left == &self.right {
return;
}
}
//handle case where all lefts are different of right
}
}

fn main() {}

但是我得到了一个:

cannot infer an appropriate lifetime for borrow expression due to conflicting requirements
--> src/main.rs:22:24
|
22 | if left == &self.right {
| ^^^^^^^^^^^
|

如何遍历 left,然后将每个元素与 right 进行比较?

最佳答案

您可以简单地要求特征绑定(bind) PartialEq<B> .方法eqne从特征中通过引用获取所有参数,因此没有理由要求 PartialEq对类型的引用。

所以这是可行的:

impl<'a, 'b, T: 'a, U> Drop for Contain<'a, 'b, T, U>
where
&'a T: IntoIterator,
<(&'a T) as IntoIterator>::Item: PartialEq<U>, // <-- change 1
{
fn drop(&mut self) {
for left in self.theory.left.into_iter() {
if left == self.right { // <-- change 2
return;
}
}
//handle case where all lefts are different of right
}
}

关于rust - 如何解决 HRTB 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51435951/

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