基本概念

chapter 3 concepts

3.1 Variables 变量

  1. mutable and immutable
  2. variables and constants
  3. shadowing

3.2 Data Types 数据类型

  1. scalar 标量
    integer: i8/i16/i32/i64/i128 u*
    float-point: f32/f64
    bool: true/false
    character: char
  2. compound 复合类型
    tuple: let (x,y,z): (i32,f64,u8) = (2, 3.14, 4);
    array: let a: [i32;5] = [3;5]; //[3,3,3,3,3]

3.3 Function 函数

1
2
3
fn fn_name(var:type,var2:type) -> ret_type {
// statements
}

语句(statement): 是一些执行动作的指令,不会返回值。(statement are instructions that perform some action and do not return value)
表达式(expression): 运行计算一个值。(expression evaluate to a resulting value)

函数调用、宏(macro)调用、{}块都是一个表达式。
表达式不用分号结束,下面的例子,如果用分号结束,就变成了一个语句,不能正确编译。

1
2
3
4
let y = {
let x=3;
x+1
}

3.4 Comments 注释

// 单行注释
Rust have another kind comments, document comments, will discuss later.

/// 文档注释
//!

/* 块注释 */

3.5 Control flow流程控制

3.5.1 if语句

1
2
3
4
5
6
7
8
let num = 6;
if number % 4 == 0 {
println!("number is divisible by 4");
} else if number % 3 == 0 {
println!("number is divisible by 3");
} else {
println!("number is not divisible by 4, 3.")
}
  • if is an expression
    1
    let num = if condition { 5 } else { 6 };

loop

1
2
3
4
5
6
7
8
9
let mut counter = 0;

let result = loop {
counter += 1;

if counter == 10 {
break counter * 2;
}
};

while

1
2
3
4
5
6
let mut number = 3;
while number != 0 {
println!("{}!", number);

number -= 1;
}

for

1
2
3
4
5
6
7
8
9
let a = [10, 20, 30, 40, 50];

for element in a.iter() {
println!("the value is: {}", element);
}

for number in (1..4).rev() { // Range 1..4
println!("{}!", number);
}
© 2023 PLAYAROUND All Rights Reserved. 本站访客数人次 本站总访问量
Theme by hiero