有没有办法在 rust 中注释一个带有可选闭包的函数?
Is there a way to annotate a function that takes an optional closure in rust?
我有一个函数,它接受一个可选的闭包并根据 return 值修改一个结构。
例如:
fn main() {
let mut s = Struct::<usize> { inner: None };
do_something(Some(|x:String|x.len()), &mut s);
println!("{:?}",s);
let mut s = Struct::<usize> { inner: None };
do_something(None, &mut s);
println!("{:?}",s);
}
fn do_something<P, T: Fn(String) -> P>(fun: Option<T>, s: &mut Struct<P>) {
*s = Struct {
inner: fun.map(|fun| fun(String::from("abc")))
};
}
#[derive(Debug)]
struct Struct<P> {
inner: Option<P>
}
这应该打印:
Struct { inner: Some(3) }
Struct { inner: None }
但现在无法编译,因为 cannot infer type for type parameter T declared on the function do_something
好的,我们试试:
let empty_function: Option<dyn Fn(String) -> usize> = None;
do_something(empty_function, &mut s);
此外,这不起作用,因为 empty_function
未调整大小。
有没有办法注释 do_something 以便在没有 Box
的情况下也能正常工作?
您可以使用 None::<T>
指定 None
的类型,并且可以使用函数指针(fn
而不是 dyn Fn
)作为基本大小的指针:
do_something(None::<fn(String) -> usize>, &mut s);
我有一个函数,它接受一个可选的闭包并根据 return 值修改一个结构。
例如:
fn main() {
let mut s = Struct::<usize> { inner: None };
do_something(Some(|x:String|x.len()), &mut s);
println!("{:?}",s);
let mut s = Struct::<usize> { inner: None };
do_something(None, &mut s);
println!("{:?}",s);
}
fn do_something<P, T: Fn(String) -> P>(fun: Option<T>, s: &mut Struct<P>) {
*s = Struct {
inner: fun.map(|fun| fun(String::from("abc")))
};
}
#[derive(Debug)]
struct Struct<P> {
inner: Option<P>
}
这应该打印:
Struct { inner: Some(3) }
Struct { inner: None }
但现在无法编译,因为 cannot infer type for type parameter T declared on the function do_something
好的,我们试试:
let empty_function: Option<dyn Fn(String) -> usize> = None;
do_something(empty_function, &mut s);
此外,这不起作用,因为 empty_function
未调整大小。
有没有办法注释 do_something 以便在没有 Box
的情况下也能正常工作?
您可以使用 None::<T>
指定 None
的类型,并且可以使用函数指针(fn
而不是 dyn Fn
)作为基本大小的指针:
do_something(None::<fn(String) -> usize>, &mut s);