文章目录
- basic knowledge
- references
basic knowledge
- the variable in Rust is not changed.
let x=5;
x=6;
Rust language promotes the concept that immutable variables are safer than variables in other programming language such as python and and are in favour of the concurrent operations.
of course,if actual coding requires more flexibility, the variable in Rust can be made mutable by adding the mut keyword.
let mut x: u32=5;
x=6;
why does Rust provide the concept of constants in addition to variable immutability?
const x:u32 =5;
-
To declare a constant, you need to use the const keyword, moreover, by convention, constants names should be defined in Capital letters separated by underscores,such as MAX_POINTS.
-
Constants cannot be declared with the mut keyword.
-
any constant must have an explicitly declared type.the following definition is incorrect.
const x=6;
- the value of a constant must be completely defined during compilation,which is a major difference from immutable variables.
- the following code can be compiled without any error.
let random_number = rand::random();
but the following code will encounter an error when compiled.
const random_number: u32 = rand::random();
by the way, Rust also has a variable type which is similar to constants,but the difference is it can be accessed in global scope and has a fixed memory address.
static STR_HELLO: &str = "Hello, world!"; // 不可变静态变量
static mut COUNTER: u32 = 0; // 可变静态变量
in addition,the static variable can be immutable ,but accessing them requires an unsafe block.
// 不可变静态变量 - 安全访问
static APP_NAME: &str = "MyApp"; // ✅ 安全// 可变静态变量 - 需要 unsafe 访问
static mut COUNTER: u32 = 0; // ❗ 声明为可变fn main() {// 访问可变静态变量需要 unsafeunsafe {COUNTER += 1; // ✅ 在 unsafe 块中访问println!("Counter: {}", COUNTER);}// COUNTER += 1; // ❌ 错误:不在 unsafe 块中
}
when a variable needs to have various type in different scope ,you can use variable shadowing ,that is say,you can use let
to delcare the same variable name again.
- Rust is a statically and strongly typed language.
category | type | explanation |
---|---|---|
scalar | i8 , i16 , i32 , i64 , i128 , isize u8 , u16 , u32 , u64 , u128 , usize | signed/uinsigned integer,isize/usize depends on the machine architecture |
f32 , f64 | float/double number,by default as f64 | |
bool | boolean,true 或 false | |
char | Unicode scalar(4 bytes) | |
compound | (T1, T2, T3, ...) | tuple:it has Fixed length and can stores elements of the various types. |
[T; N] | array:it has Fixed length and stores elements of the same type. The data is stored on the stack. |
furthermore,the dynamically resizable collections can use Vec<T>
,String
, and so on.they are allocated in the heap,but they are not primitive data types,in fact,they are part of standard library.
- function
character | grammer example | explanation |
---|---|---|
function definition | fn function_name() { ... } | use fn keyword |
arguments | fn foo(x: i32, y: String) | the arguments must explicitly declare type |
return value | fn foo() -> i32 { ... } | it is followed by -> to declare the return type. |
implicitly return | fn foo() -> i32 { 5 } | the return value is the last expression without semicolon in function body |
explicitly return | fn foo() -> i32 { return 5; } | to return early from a function,you can use return keyword. |
function pointer | let f: fn(i32) -> i32 = my_function; | function can be passed as value and used. |
发散函数 | fn bar() -> ! { loop {} } | 用 ! 标记,表示函数永不返回 |
4 . 控制语句
- Rust 的控制语句主要分为两类:条件分支 和 循环,它们都是表达式。
- if 表达式允许你根据条件执行不同的代码分支,格式为 :if…else或者if…else if…else…。
- loop 关键字会创建一个无限循环,直到显式地使用 break 跳出。可以在 break 后跟一个表达式,这个表达式将成为 loop 表达式的返回值。continue也可以像其它语言一样使用。
- while 循环在条件为 true 时持续执行。
- for 循环遍历集合。如下所示。
fn main() {let x = [11, 12, 13, 14, 15];for element in x {println!("the value is: {}", element);}// 或者使用迭代器for element in x.iter() {println!("the value is: {}", element);}
}
range
由标准库提供,生成一个数字序列。
(1..4):生成 1, 2, 3(不包含结束值)。(1..=4):生成 1, 2, 3, 4(包含结束值)。(start..end).rev():可以反转范围。
- match可进行模式匹配和穷尽性检查。match根据一个值的不同情况,执行不同的代码并返回相应的结果。
fn main() {let number = 3;// 使用 match 将数字转换为星期几let day = match number {1 => "星期一",2 => "星期二", 3 => "星期三",4 => "星期四",5 => "星期五",6 => "星期六",7 => "星期日",_ => "无效的数字,请输入1-7", // _ 通配符处理所有其他情况};println!("数字 {} 对应的是: {}", number, day);
}
references
- https://www.rust-lang.org/learn/
- deepseek