gpt4 book ai didi

rust - 将闭包传递给需要 std::ops::Fn 的函数

转载 作者:行者123 更新时间:2023-11-29 07:59:37 25 4
gpt4 key购买 nike

<分区>

我正在尝试使用闭包来调用一组特征向量上的函数。这里最重要的代码行是第一行,我们在这里说什么类型 query必须是最后一行,我们尝试在此结束。

fn stat_query(dataset: &Vec<Vec<i32>>, query: Fn(&Vec<i32>) -> f64) -> f64 {
// takes in a dataset of feature vectors and a query,
// returns the average of the query on the dataset
if dataset.len() == 0 {
0.
} else {
dataset.iter().map(|ref fv| query(&fv)).sum() / (dataset.len() as f64)
}
}

fn main() {
// build dataset
let fv1: Vec<i32> = vec![1, 1, 1, 1, 1];
let fv2: Vec<i32> = vec![1, 0, 1, 0, 1];
let my_dataset = vec![fv1, fv2];

// query checks whether sum of features is greater than a threshold
fn my_query(ref fv: &Vec<i32>, threshold: i32) -> f64 {
if fv.iter().sum() > threshold {
1.
} else {
0.
}
}

// run query on dataset with threshold 3
println!("{}", stat_query(&my_dataset, |ref fv| my_query(fv, 3)));
}

当我运行它时,出现错误:

error[E0277]: the trait bound `for<'r> std::ops::Fn(&'r std::vec::Vec<i32>) -> f64 + 'static: std::marker::Sized` is not satisfied
--> src/main.rs:1:40
|
1 | fn stat_query(dataset: &Vec<Vec<i32>>, query: Fn(&Vec<i32>) -> f64) -> f64 {
| ^^^^^ `for<'r> std::ops::Fn(&'r std::vec::Vec<i32>) -> f64 + 'static` does not have a constant size known at compile-time
|
= help: the trait `std::marker::Sized` is not implemented for `for<'r> std::ops::Fn(&'r std::vec::Vec<i32>) -> f64 + 'static`
= note: all local variables must have a statically known size

error[E0308]: mismatched types
--> src/main.rs:27:44
|
27 | println!("{}", stat_query(&my_dataset, |ref fv| my_query(fv, 3)));
| ^^^^^^^^^^^^^^^^^^^^^^^^ expected trait std::ops::Fn, found closure
|
= note: expected type `for<'r> std::ops::Fn(&'r std::vec::Vec<i32>) -> f64 + 'static`
found type `[closure@src/main.rs:27:44: 27:68]`

我以为闭包implemented Fn (或 FnOnceFnMut )?当您期望 Fn 时,提供闭包是否无效? ?我假设我需要指定关于 Fn 的其他内容在第一行?但是什么?

我假设我错误地指定了 query: Fn(&Vec<i32>) -> f64 的类型我的第一个函数的参数,或者闭包写错了|ref fv| my_query(fv, 3) .

我读了Passing closure to trait method: expected type parameter, found closure ,但这似乎更多地是关于传递一个不是函数接受的唯一类型的闭包。

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