ํ๋ฆ ์ ์ด
Rust์๋ ๋ค๋ฅธ ์ธ์ด์๋ ๋ค๋ฅธ ๋ช ๊ฐ์ง ์ ์ด ํ๋ฆ ๊ตฌ์กฐ๊ฐ ์์ผ๋ฉฐ ํจํด ์ผ์น์ ์ฌ์ฉ๋ฉ๋๋ค.
if let
ํํ์while let
expressionsmatch
ํํ์
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 let
loop as an infinite loop with an if statement that breaks when there is no value to unwrap forname.pop()
. Thewhile let
provides syntactic sugar for the above scenario.