我可以在Rust中传递函数作为参数(可能是的),如果可以的话,我可以这么做.
如果你不能,这是一个很好的选择.
我尝试了一些语法,但我没有得到
我知道我能做到这一点
fn example() {
let fun: fn(value: i32) -> i32;
fun = fun_test;
fun(5i32);
}
fn fun_test(value: i32) -> i32 {
println!("{}", value);
value
}
Run Code Online (Sandbox Code Playgroud)
但不是将函数作为参数传递给另一个函数
fn fun_test(value: i32, (some_function_prototype)) -> i32 {
println!("{}", value);
value
}
Run Code Online (Sandbox Code Playgroud) 考虑以下玩具示例:
use std::cmp::Ordering;
pub trait SimpleOrder {
fn key(&self) -> u32;
}
impl PartialOrd for dyn SimpleOrder {
fn partial_cmp(&self, other: &dyn SimpleOrder) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for dyn SimpleOrder {
fn cmp(&self, other: &dyn SimpleOrder) -> Ordering {
self.key().cmp(&other.key())
}
}
impl PartialEq for dyn SimpleOrder {
fn eq(&self, other: &dyn SimpleOrder) -> bool {
self.key() == other.key()
}
}
impl Eq for SimpleOrder {}
Run Code Online (Sandbox Code Playgroud)
这不编译.它声称在实施过程中存在一个终身问题partial_cmp:
error[E0495]: cannot infer an appropriate lifetime due …Run Code Online (Sandbox Code Playgroud) 鉴于以下代码段:
use futures::stream::{self, StreamExt};
async fn from_bar(bar: &[Vec<&u8>]) {
let x = bar.iter().flat_map(|i| i.iter().map(|_| async { 42 }));
let foo: Vec<_> = stream::iter(x).collect().await;
}
#[tokio::main]
async fn main() {
for bar in vec![] {
tokio::spawn(async {
from_bar(bar).await;
});
}
}
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
error[E0308]: mismatched types
--> src/main.rs:11:9
|
11 | tokio::spawn(async {
| ^^^^^^^^^^^^ one type is more general than the other
|
= note: expected type `std::ops::FnOnce<(&&u8,)>`
found type `std::ops::FnOnce<(&&u8,)>`
error: implementation of `std::iter::Iterator` is not general …Run Code Online (Sandbox Code Playgroud)