Struct, enum và trait

Rust Option: Some and None

Rust has no null. A value that may be missing is an Option, and the compiler makes you handle None.

  • Trung cấp
  • Đọc trong 3 phút
  • 1 ví dụ chạy được
Bạn sẽ học được gì
  • Some(value) and None
  • match and unwrap_or
  • map on an Option
find_user(id)
Some
  • id 1 → Some("Ada")
  • use the name
None
  • id 3 → None
  • handle the missing case

A value that may be missing

Rust has no null. A value that may be missing has the type Option<T>, which is either Some(value) or None. The compiler makes you handle the None case before you can use the value.

find_user returns Some for a known id and None otherwise, and match handles both. unwrap_or supplies a default when the value is missing. map changes the value inside Some and leaves None alone.

Những điểm quan trọng

  1. Option<T> is Some(value) or None.
  2. unwrap_or gives a default.
  3. map changes the value inside Some.

Ví dụ Rust chạy được

Rust
Chạy code →
main.rs
fn find_user(id: u32) -> Option<&'static str> {
    match id {
        1 => Some("Ada"),
        2 => Some("Linus"),
        _ => None,
    }
}

fn main() {
    for id in [1, 3] {
        match find_user(id) {
            Some(name) => println!("user {id}: {name}"),
            None => println!("user {id}: not found"),
        }
    }

    let name = find_user(9).unwrap_or("guest");
    println!("{name}");

    let length = find_user(2).map(|name| name.len());
    println!("{:?}", length);
}
Lấy nút Run cho ví dụ này Kết quả khi chạy
user 1: Ada
user 3: not found
guest
Some(5)

Luyện tập

Mở ví dụ trong trình biên dịch online, đổi một giá trị hoặc thêm một dòng, rồi đoán kết quả trước khi chạy. Sau đó cố ý làm code bị lỗi và đọc thông báo của trình biên dịch.

Bạn học xong bài này chưa?

Đánh dấu đã học để theo dõi tiến độ của bạn.

Luyện tập với thử thách

Áp dụng kiến thức của bài học này để giải một bài toán thực tế. Mỗi thử thách chạy ngay trên trình duyệt, có kiểm thử tức thì và AI nhận xét.

Tất cả thử thách