0
已有513人阅读此文 - - Rust - luoyy -

函数(fn)

fn关键字声明新函数

fn main() {
    println!("Hello, world!");

    another_function();
}

fn another_function() {
    println!("Another function.");
}

参数

fn main() {
    print_labeled_measurement(5, 'h');
}

fn print_labeled_measurement(value: i32, unit_label: char) {
    println!("The measurement is: {value}{unit_label}");
}

声明和表达式

  • 声明(Statements) 是执行某些操作但不返回值的指令。
  • 表达式(Expressions) 计算结果值。
fn main() {
    let y = {
        let x = 3;
        x + 1
    };

    println!("The value of y is: {y}");
}

这个表达式:

{
    let x = 3;
    x + 1
}

是一个块,在本例中,其计算结果为4。y 该值作为语句的一部分进行绑定let。请注意,该x + 1行末尾没有分号(;),这与您迄今为止看到的大多数行不同。表达式不包含结束分号。如果在表达式末尾添加分号,则将其转换为语句,并且它不会返回值。当您接下来探索函数返回值和表达式时,请记住这一点。

有返回值的函数

不命名返回值,但必须在箭头 ( ->) 之后声明它们的类型。在 Rust 中,函数的返回值与函数体块中最终表达式的值同义。return您可以通过使用关键字并指定值从函数中提前返回,但大多数函数都会隐式返回最后一个表达式

fn five() -> i32 {
    5
}

fn main() {
    let x = five();

    println!("The value of x is: {x}"); // 5
}
fn five() -> i32 {
    return 5;
}

fn main() {
    let x = five();

    println!("The value of x is: {x}"); // 5
}

注释

源代码中留下注释,编译器会忽略这些注释,但阅读源代码的人可能会发现有用

fn main() {
    // I’m feeling lucky today
    let _lucky_number = 7;

    // So we’re doing something complicated here, long enough that we need
    // multiple lines of comments to do it! Whew! Hopefully, this comment will
    // explain what’s going on.
    test();
}

/**
 * test
 */
fn test() -> i64 {
    8
}

/// Adds one to the number given.
///
/// # Examples
///
/// ```
/// let arg = 5;
/// let answer = my_crate::add_one(arg);
///
/// assert_eq!(6, answer);
/// ```
pub fn add_one(x: i32) -> i32 {
    x + 1
}


无意义的注释会被编译器告警

期待你一针见血的评论,Come on!

发表评论: