简体   繁体   English

有没有办法注释 function 在 rust 中采用可选闭包?

[英]Is there a way to annotate a function that takes an optional closure in rust?

I have a function that takes an optional closure and modifies a struct based on the return value.我有一个 function 采用可选的闭包并根据返回值修改结构。

For example:例如:

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>
}

This should print:这应该打印:

Struct { inner: Some(3) }
Struct { inner: None }

But now it doesn't compile, since cannot infer type for type parameter T declared on the function do_something但现在它无法编译,因为cannot infer type for type parameter T declared on the function do_something

Ok, let's try:好的,让我们试试:

  let empty_function: Option<dyn Fn(String) -> usize> = None;
  do_something(empty_function, &mut s);

Also, doesn't work, since empty_function is unsized.此外,也不起作用,因为empty_function没有大小。

Is there a way annotate do_something so that this would work without Box ?有没有办法注释 do_something 以便在没有Box的情况下工作?

You can specify the type of None with None::<T> and you can use function pointers ( fn rather than dyn Fn ) as basic sized pointers:您可以使用None::<T>指定None的类型,并且可以使用 function 指针( fn而不是dyn Fn )作为基本大小的指针:

do_something(None::<fn(String) -> usize>, &mut s);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM