Archive/Rust

[Rustlings] 13. Option

 Option은 Rust의 타입 중 하나로 어떤 값을 가지는 Some<T>과 값을 가지지 않는 None이 있다. Option은 Rust에서 다양하게 사용된다. 보통 값을 가지지 않는 경우도 오류 없이 처리할 수 있도록 만들기 위해 사용한다.

struct Option<T> {
  Some(T),
  None,
}

 Option 값을 처리할 때는 보통 match을 사용한다. 종종 match를 사용하여 조건문이나 반복문을 돌리는 경우가 많아 Rust에서는 if letwhile let으로 따로 문법을 제공한다.

if let Some(word) = optional_input {
  println!("{}", word);
} else {
  println!("Input a vaild word");
}

while let Some(i) = vec.pop() {
  println!("{}", i);
}

if let은 주어진 값(optional_input)이 패턴(Some(word))과 일치하는지 판단하고 참거짓에 따라 처리한다. while let의 경우도 패턴(Some(i))이 계속 일치하는 경우에만 반복한다.

'Archive > Rust' 카테고리의 다른 글

[Rustlings] 15. trait  (0) 2021.05.31
[Rustlings] 14. Result  (0) 2021.05.30
[Rustlings] 12. Generic  (0) 2021.05.29
[Rustlings] 11. Error Handling  (0) 2021.05.28
[Rustlings] 10. String  (0) 2021.05.26