【发布时间】:2016-08-01 17:07:57
【问题描述】:
使用rustc 1.10.0,我正在尝试编写一些绕过盒装闭包的代码——最终目标是在程序上生成分形动画。现在我有一些这样的函数签名:
pub fn interpolate_rectilinear(width: u32, height: u32, mut min_x: f64, mut max_x: f64, mut min_y: f64, mut max_y: f64)
-> Box<Fn(u32, u32) -> Complex64 + Send + Sync + 'static> { ... }
pub fn interpolate_stretch(width: u32, height: u32, mut min_x: f64, mut max_x: f64, mut min_y: f64, mut max_y: f64)
-> Box<Fn(u32, u32) -> Complex64 + Send + Sync + 'static> { ... }
pub fn parallel_image<F>(width: u32, height: u32, function: &F, interpolate: &Box<Fn(u32, u32) -> Complex64 + Send + Sync>, threshold: f64)
-> ImageBuffer<image::Luma<u8>, Vec<u8>>
where F: Sync + Fn(Complex64) -> Complex64
{ ... }
pub fn sequential_image<F>(width: u32, height: u32, function: &F, interpolate: &Box<Fn(u32, u32) -> Complex64>, threshold: f64)
-> ImageBuffer<image::Luma<u8>, Vec<u8>>
where F: Fn(Complex64) -> Complex64
{ ... }
在二进制文件中一次为一个图像运行此代码没有问题:
let interpolate = interpolate_rectilinear(width, height, -1.0, 1.0, -1.0, 1.0);
let image = parallel_image(width * 2, height * 2, &default_julia, &interpolate, 2.0);
但是,我想确保我的串行和并行图像生成都产生相同的结果,所以我编写了以下测试函数:
#[test]
fn test_serial_parallel_agree() {
let (width, height) = (200, 200);
let threshold = 2.0;
let interpolate = interpolate_stretch(width, height, -1.0, 1.0, -1.0, 1.0);
assert!(parallel_image(width, height, &default_julia, &interpolate, threshold)
.pixels()
.zip(sequential_image(width, height, &default_julia, &interpolate, threshold)
.pixels())
.all(|(p, s)| p == s));
}
这拒绝编译,我就是想不通。它给出的错误如下:
> cargo test
Compiling julia-set v0.3.0
src/lib.rs:231:66: 231:78 error: mismatched types [E0308]
src/lib.rs:231 .zip(sequential_image(width, height, &default_julia, &interpolate, threshold)
^~~~~~~~~~~~
src/lib.rs:229:9: 233:36 note: in this expansion of assert! (defined in <std macros>)
src/lib.rs:231:66: 231:78 help: run `rustc --explain E0308` to see a detailed explanation
src/lib.rs:231:66: 231:78 note: expected type `&Box<std::ops::Fn(u32, u32) -> num::Complex<f64> + 'static>`
src/lib.rs:231:66: 231:78 note: found type `&Box<std::ops::Fn(u32, u32) -> num::Complex<f64> + Send + Sync>`
error: aborting due to previous error
Build failed, waiting for other jobs to finish...
error: Could not compile `julia-set`.
我真的不知道那里发生了什么。我不知道为什么我需要在插值函数的盒装返回类型中手动标记Send 和Sync,而编译器通常会自动派生这些特征。不过,我只是不断添加编译器建议的标记,直到一切正常。
真正的问题是,虽然我想我已经很好地猜到了为什么你不能只标记一个盒装的闭包'static,但我不知道在这种情况下需要什么生命周期或如何解决它。
我确实猜想问题可能是我试图同时从两个读取借阅中引用闭包(这应该没问题,但我很绝望);无论如何,将interpolate 包装在Rc 中会产生完全相同的错误,所以这不是问题。
【问题讨论】:
-
你有 git repo 之类的吗?我想测试一下。
-
除了 Veedrac 的评论之外,您应该在 Stack Overflow 上提问时提供minimal reproducible example(真的在任何地方,但尤其是在这里)。如果我们无法完全从此处中包含的内容重现您的问题,那么问题将结束。
-
@coriolinus:我想你误会了。目的是减少问题,直到它只有几行并且不需要任何板条箱。一旦您设法减少问题,您很可能最终会回答自己的问题。
-
遗憾的是这是不可能的:play.rust-lang.org/… 仍然依赖于其他 crate 和此处未提供的类型。我们显然可以自己完成这项工作,但是您可以通过提供这样一个“可编译”示例来激发帮助。显然它不会编译,但它会产生你显示的确切错误。
标签: closures rust lifetime-scoping