νλ¦ μ μ΄
Rustμλ λ€λ₯Έ μΈμ΄μλ λ€λ₯Έ λͺ κ°μ§ μ μ΄ νλ¦ κ΅¬μ‘°κ° μμΌλ©° ν¨ν΄ μΌμΉμ μ¬μ©λ©λλ€.
if letννμwhile letexpressionsmatchννμ
if let ννμ
if let ννμμ μ¬μ©νλ©΄ κ°μ΄ ν¨ν΄κ³Ό μΌμΉνλμ§μ λ°λΌ λ€λ₯Έ μ½λλ₯Ό μ€νν μ μμ΅λλ€:
fn sleep_for(secs: f32) { let dur = if let Ok(dur) = std::time::Duration::try_from_secs_f32(secs) { dur } else { std::time::Duration::from_millis(500) }; std::thread::sleep(dur); println!("{:?} λμ μ λ€μμ΅λλ€.", dur); } fn main() { sleep_for(-10.0); sleep_for(0.8); }
let else expressions
ν¨ν΄μ μΌμΉμν€κ³ ν¨μμμ λ°ννλ μΌλ°μ μΈ κ²½μ°μλ let elseλ₯Ό μ¬μ©ν©λλ€. βelseβ μ¬λ‘λ ν΄λΉ μ½λλ₯Ό λ²μ΄λμΌ ν©λλ€ (return, break λλ ν¨λ - λΈλ‘μ λ€μ μμΉλ‘ μ΄λνλ κ²λ§ μλλ©΄ λ©λλ€).
fn hex_or_die_trying(maybe_string: Option<String>) -> Result<u32, String> { let s = if let Some(s) = maybe_string { s } else { return Err(String::from("Noneμ κ°μ Έμ΄")); }; let first_byte_char = if let Some(first_byte_char) = s.chars().next() { first_byte_char } else { return Err(String::from("got empty string")); }; if let Some(digit) = first_byte_char.to_digit(16) { Ok(digit) } else { Err(String::from("16μ§μκ° μλ")) } } fn main() { println!("κ²°κ³Ό: {:?}", hex_or_die_trying(Some(String::from("foo")))); }
λ§μ§λ§μΌλ‘, 무ν 루νλ₯Ό λ§λλ loop ν€μλκ° μμ΅λλ€:
fn main() { let mut name = String::from("Comprehensive Rust π¦"); while let Some(c) = name.pop() { println!("character: {c}"); } // (There are more efficient ways to reverse a string!) }
Here String::pop returns Some(c) until the string is empty, after which it will return None. The while let lets us keep iterating through all items.
if-let
if letμ΄matchλ³΄λ€ λ κ°κ²°ν μ μμ΅λλ€(μ: νκ°μ§ λΈλμΉλ§ ν₯λ―Έλ‘μ΄ κ²½μ°). μ΄μ λ¬λ¦¬matchμμλ λͺ¨λ λΈλμΉκ° μ²λ¦¬λμ΄μΌ ν©λλ€.- μΌλ°μ μ¬μ©λ²μ
Optionμ μ¬μ©ν λSomeκ°μ μ²λ¦¬νλ κ²μ λλ€. matchμ λ¬λ¦¬if letμ ν¨ν΄ μΌμΉλ₯Ό μν λ³΄νΈ μ μ μ§μνμ§ μμ΅λλ€.
let-else
μμμ λ³Έ κ²μ²λΌ if-letμ μ€μ²©ν μ μμ΅λλ€. let-else ꡬ쑰λ μ΄ μ€μ²©λ μ½λμ νλ©΄νλ₯Ό μ§μν©λλ€. μ½λκ° μ΄λ»κ² λ³ννλμ§ νμλ€μ΄ λ³Ό μ μλλ‘ μ΄μν λ²μ μ λ€μ μμ±νμΈμ.
λ€μ μμ±λ λ²μ μ λ€μκ³Ό κ°μ΅λλ€.
#![allow(unused)] fn main() { fn hex_or_die_trying(maybe_string: Option<String>) -> Result<u32, String> { let Some(s) = maybe_string else { return Err(String::from("Noneμ κ°μ Έμ΄")); }; let Some(first_byte_char) = s.chars().next() else { return Err(String::from("got empty string")); }; let Some(digit) = first_byte_char.to_digit(16) else { return Err(String::from("16μ§μκ° μλ")); }; return Ok(digit); } }
while-let
while letμ κ°μ΄ ν¨ν΄μ λ§€μΉλλ λμ κ³μλ©λλ€.- You could rewrite the
while letloop as an infinite loop with an if statement that breaks when there is no value to unwrap forname.pop(). Thewhile letprovides syntactic sugar for the above scenario.