当前位置:网站首页>005. Functions in rust

005. Functions in rust

2020-12-06 14:41:20 ryanliue

1、 Definition of function
We define a simple function with no parameters and no return value :

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

fn main() {
    other_fun();
}

2、 Functions with parameters :

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、 The return value of the function :

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、 The difference between a statement and an expression :

let y = 1; // sentence , No return value 
// let x = (let y = 1);
let y = { // expression , Calculates and returns a value 
    let x = 1;
    x + 1
};
println!("y = {}", y);

learn_fn/src/main.rs Full source code :
https://github.com/anonymousGiga/learn_rust/blob/master/learn_fn/src/main.rs

版权声明
本文为[ryanliue]所创,转载请带上原文链接,感谢
https://chowdera.com/2020/12/20201206143600383q.html