구조체, 열거형, 트레이트

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.

  • 중급
  • 3분 분량
  • 실행 가능한 예제 1개
배울 내용
  • 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.

핵심 포인트

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

실행 가능한 Rust 예제

Rust
코드 실행 →
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);
}
이 예제의 실행 버튼 만들기 코드 실행 결과
user 1: Ada
user 3: not found
guest
Some(5)

연습

예제를 온라인 컴파일러에서 열고 값을 바꾸거나 한 줄을 추가한 다음, 실행하기 전에 출력을 예상해 보세요. 그런 다음 일부러 코드를 망가뜨리고 컴파일러 메시지를 읽어 보세요.

이 레슨을 마쳤나요?

학습 완료로 표시하면 진행 상황을 기록할 수 있습니다.

다음: Error Handling with Result →

챌린지로 연습하기

이 레슨에서 배운 내용으로 실제 문제를 풀어 보세요. 모든 챌린지는 브라우저에서 실행되며 즉시 테스트와 AI 리뷰를 받을 수 있습니다.

모든 챌린지