daily notes[45]
本文介绍了Rust语言中变量的不可变性特性及其相关概念。Rust默认变量不可变(如let x=5),这有利于并发安全,但可通过mut关键字设为可变。此外,R
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() {
// 访问可变静态变量需要 unsafe
unsafe {
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. |
Divergent function | fn bar() -> ! { loop {} } |
flag it with ! ,which means the function never returned . |
4 . control statement
- the control flow in Rust mainly falls into two categories:conditional statements and loops,please note that they are expressions.
- An
if
expression runs various code blocks depending on different conditions.Its syntax can beif...else...
orif...else if....else...
- the loop keyword creates an infinite loop,which is exited exited when a break is explicitly used.
Additionally, an expression can follow the break keyword ,this expression then becomes the return value of the entire loop statement.
of couse, the continue keyword also can be used, similar to other programming language. - while loop executes continously when the condition is true.
- A for loop iterates through a set in a circular manner,for example:
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
function,which is provided by the standard library ,generates series of numbers.
(1..4):生成 1, 2, 3(不包含结束值)。
(1..=4):生成 1, 2, 3, 4(包含结束值)。
(start..end).rev():可以反转范围。
- match keyword is used for pattern matching and exhaustive check,it runs different code blocks and returns the appropriate result based on various cases of a value.
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
更多推荐
所有评论(0)