文章目錄
- 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