当前位置:网站首页>005、Rust中的函数

005、Rust中的函数

2020-12-06 14:41:20 ryanliue

1、函数的定义
我们定义一个简单的没有参数也没有返回值的函数:

fn other_fun() {
    println!("This is a function");
}

fn main() {
    other_fun();
}

2、有参数的函数:

fn other_fun1(a: i32, b: u32) {
    println!("a = {}, b = {}", a, b);
}

fn main() {
    let a: i32 = -1;
    let b: u32 = 2;
    other_fun1(a, b);
}

3、函数的返回值:

fn other_fun2(a: i32, b: i32) -> i32 {
    let result = a + b;
    result
}

fn main() {
    let c: i32 = -1;
    let d: i32 = 9;
    let r = other_fun2(c, d);
    println!("r = {}", r);
}

4、语句和表达式的区别:

let y = 1; //语句,不返回值
// let x = (let y = 1);
let y = { //表达式,计算并返回值
    let x = 1;
    x + 1
};
println!("y = {}", y);

learn_fn/src/main.rs完整源代码:
https://github.com/anonymousGiga/learn_rust/blob/master/learn_fn/src/main.rs

版权声明
本文为[ryanliue]所创,转载请带上原文链接,感谢
https://my.oschina.net/u/943779/blog/4776946