当我试图编译下面的Rust代码时,遇到了一对奇怪的错误。在寻找类似问题的其他人时,我发现另一个具有相同组合(看似相反)错误的问题, 但无法将该解决方案推广到我的问题。
基本上,我似乎在Rust的所有权系统中缺少微妙之处。在尝试编译此处(非常精简的)代码时:
struct Point {
x: f32,
y: f32,
}
fn fold<S, T, F>(item: &[S], accum: T, f: F) -> T
where
F: Fn(T, &S) -> T,
{
f(accum, &item[0])
}
fn test<'a>(points: &'a [Point]) -> (&'a Point, f32) {
let md = |(q, max_d): (&Point, f32), p: &'a Point| -> (&Point, f32) {
let d = p.x + p.y; // Standing in for a function call
if d > max_d {
(p, d)
} else {
(q, max_d)
}
};
fold(&points, (&Point { x: 0., y: 0. }, 0.), md)
}
我收到了以下错误信息:
error[E0631]: type mismatch in closure arguments
--> src/main.rs:23:5
|
14 | let md = |(q, max_d): (&Point, f32), p: &'a Point| -> (&Point, f32) {
| ---------------------------------------------------------- found signature of `for<'r> fn((&'r Point, f32), &'a Point) -> _`
...
23 | fold(&points, (&Point { x: 0., y: 0. }, 0.), md)
| ^^^^ expected signature of `for<'r> fn((&Point, f32), &'r Point) -> _`
|
= note: required by `fold`
error[E0271]: type mismatch resolving `for<'r> <[closure@src/main.rs:14:14: 21:6] as std::ops::FnOnce<((&Point, f32), &'r Point)>>::Output == (&Point, f32)`
--> src/main.rs:23:5
|
23 | fold(&points, (&Point { x: 0., y: 0. }, 0.), md)
| ^^^^ expected bound lifetime parameter, found concrete lifetime
|
= note: required by `fold`
(这是一个Rust Playground链接,方便查看代码。)
我认为我提供给fold
函数的函数应该能够正确地进行类型检查... 我错过了什么,我该如何解决?
&[T]
代替&Vec<T>
。此外,当一个空向量被传递给您的test
函数时会发生什么?那个引用会在哪里存在? - ShepmasterVec<T>
来代替我正在开发的自定义函数式列表类型,只是为了保持问题简单并关注我得到的错误。此外,在我的代码的非精简版本中,一个空列表会导致panic!
并显示没有任何事可做。基本上,我尝试将代码简化到仍然可以获得错误消息的地步,同时省略任何多余的东西。 - Trevor&Vec<T>
,所以它甚至不应该出现在示例中 ^_^。 - Shepmaster