rust学习_函数

定义函数1.定义函数使用fn关键字。 
2.函数可以有参数 也可以没有
3.函数可以有返回值 也可以不返回值

fn function_name(parameters) -> return_type {
    //函数体
    //最后一个表达式通常是返回值(如果
没有分号
}
不带参数的函数fn main() {
      say_hello()
}

fn say_hello() {
     println!("hello,world");
}
带参数的函数fn main() {
    let name = "Alice";
    greet(name);
}

fn greet(name: &str) {
    println!("Hello, {}!", name);
}
返回值的函数fn main() {
    let result = add(5, 3);
    println!("The result is {}", result);
}

fn add(x: i32, y: i32) -> i32 {
    x + y // 这里没有分号,所以这是返回值
}
函数中的表达式1.表达式是什么
    1.表达式是计算某个值的代码片段 
    2.表达式不以分号(;)结束
    3.如  x+1 就是表达式

2.举例:
fn calculate(x: i32, y: i32) -> i32 {
    let z = x * y;
    z + 10  // 这里是返回值
}
控制流 1.函数中可以使用 if  loop for  while等循环
fn main() {
    let number = 6;

    if number % 4 == 0 {
        println!("number is divisible by 4");
    } else if number % 3 == 0 {
        println!("number is divisible by 3");
    } else if number % 2 == 0 {
        println!("number is divisible by 2");
    } else {
        println!("number is not divisible by 4, 3, or 2");
    }
}   
函数中使用闭包fn main() {
    let plus_one = |x: i32| -> i32 { x + 1 };
    let result = plus_one(5);
    println!("The result is {}", result);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

simper_zxb

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值