Doko's new lair
Rust

(VN) Rusty Diary (02)

Rusty diary, part 2

Immutable

Mặc định biến trong rust là immutable, trừ khi dùng mut, nên nếu:

fn main() {
    let x = 5;
    println!("The value of x is: {}", x);
    x = 6;
    println!("The value of x is: {}", x);
}

sẽ có lỗi:

$ cargo run
   Compiling variables v0.1.0 (file:///projects/variables)
error[E0384]: cannot assign twice to immutable variable `x`
 --> src/main.rs:4:5
  |
2 |     let x = 5;
  |         -
  |         |
  |         first assignment to `x`
  |         help: make this binding mutable: `mut x`
3 |     println!("The value of x is: {}", x);
4 |     x = 6;
  |     ^^^^^ cannot assign twice to immutable variable

error: aborting due to previous error

For more information about this error, try `rustc --explain E0384`.
error: could not compile `variables`.

To learn more, run the command again with --verbose.

Nên chỉnh lại là:

fn main() {
    let mut x = 5;
    println!("The value of x is: {}", x);
    x = 6;
    println!("The value of x is: {}", x);
}

Kết quả:

$ cargo run
   Compiling variables v0.1.0 (file:///projects/variables)
    Finished dev [unoptimized + debuginfo] target(s) in 0.30s
     Running `target/debug/variables`
The value of x is: 5
The value of x is: 6

mut với const...

... không đi cùng nhau được, vì như tên gọi, const luôn bất biến. Hơn nữa:

The last difference is that constants may be set only to a constant expression, not the result of a function call or any other value that could only be computed at runtime.

VD:

#![allow(unused)]
fn main() {
const MAX_POINTS: u32 = 100_000;
}

Shadowing

Là kiểu khai báo đè lên nhau được. Với các ngôn ngữ khác như Java thì như này là lỗi:

int a = 2;
int a = 12;

a được khai báo rồi, không khai báo lại được, nhưng với rust thì được:

fn main() {
    let x = 5;

    let x = x + 1;

    let x = x * 2;

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

Tuple

Một nhóm các giá được đưa vào 1 biến. Gần giống mảng nhưng strict hơn:

fn main() {
    let tup: (i32, f64, u8) = (500, 6.4, 1);
}

và cũng có cách để destructure giống Javascript ES6:

fn main() {
    let tup = (500, 6.4, 1);

    let (x, y, z) = tup;

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

Array

Rust tất nhiên có array:

fn main() {
    let a = [1, 2, 3, 4, 5];
}

để chỉ định tường minh một array, bao gồm kiểu dữ liệu và kích thước:

#![allow(unused)]
fn main() {
let a: [i32; 5] = [1, 2, 3, 4, 5];
}