# 高阶函数

## 函数类型

The function type constructor fn forms new function types. A function type consists of a possibly-empty set of function-type modifiers (such as unsafe or extern), a sequence of input types and an output type.

fn inc(n: i32) -> i32 {//函数定义
n + 1
}

type IncType = fn(i32) -> i32;//函数类型

fn main() {
let func: IncType = inc;
println!("3 + 1 = {}", func(3));
}

fn main() {
let func: IncType = inc;
println!("3 + 1 = {}", func(3));
println!("3 + 1 = {}", inc(3));
}

type IncType = fn(i32) -> i32;

fn inc(n: i32) -> i32 {
n + 1
}

3 + 1 = 4
3 + 1 = 4

## 函数作为参数

fn main() {
println!("3 + 1 = {}", process(3, inc));
println!("3 - 1 = {}", process(3, dec));
}

fn inc(n: i32) -> i32 {
n + 1
}

fn dec(n: i32) -> i32 {
n - 1
}

fn process(n: i32, func: fn(i32) -> i32) -> i32 {
func(n)
}

3 + 1 = 4
3 - 1 = 2

fn process<F>(n: i32, func: F) -> i32
where F: Fn(i32) -> i32 {
func(n)
}

## 函数作为返回值

fn main() {
let a = [1,2,3,4,5,6,7];
let mut b = Vec::<i32>::new();
for i in &a {
b.push(get_func(*i)(*i));
}
println!("{:?}", b);
}

fn get_func(n: i32) -> fn(i32) -> i32 {
fn inc(n: i32) -> i32 {
n + 1
}
fn dec(n: i32) -> i32 {
n - 1
}
if n % 2 == 0 {
inc
} else {
dec
}
}

fn main() {
let f = get_func();
println!("{}", f(3));
}

fn get_func() -> fn(i32)->i32 {
let a = 1;
fn inc(n:i32) -> i32 {
n + a
}
inc
}