Rust作为输出参数

闭包作为输入参数是可能的,所以返回一个也应该是可能的。然而,闭合返回类型是有问题的,因为Rust目前只支持返回泛型(非通用)类型。匿名闭合类型是,根据定义,未知等返回闭合只能通过使它具体。这可以通过装箱来完成。

有效类型返回也比以前略有不同:

  • Fn: 通常
  • FnMut: 通常
  • FnBox: 相当于 FnOnce 但专门为这个应用程序,因为目前FnOnce(版本1.1.0)严重交互类型系统。

除此之外,move 关键字必须使用这标志着捕获值。这是必需的,因为通过引用任何捕获会尽快丢弃,函数退出后在闭合内是无效的引用。 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#![feature(fnbox)]
use std::boxed::FnBox;
// Return a closure taking no inputs and returning nothing
// which implements `FnBox` (capture by value).
fn create_fnbox() -> Box {
let text = "FnBox".to_owned();
Box::new(move || println!("This is a: {}", text))
}
fn create_fn() -> Box {
let text = "Fn".to_owned();
Box::new(move || println!("This is a: {}", text))
}
fn create_fnmut() -> Box {
let text = "FnMut".to_owned();
Box::new(move || println!("This is a: {}", text))
}
fn main() {
let fn_plain = create_fn();
let mut fn_mut = create_fnmut();
let fn_box = create_fnbox();
fn_plain();
fn_mut();
fn_box();
}
联系我们

邮箱 626512443@qq.com
电话 18611320371(微信)
QQ群 235681453

Copyright © 2015-2024

备案号:京ICP备15003423号-3