ํ ์คํธ
Rust์๋ ์์์ ํ์
๋ณํ์ด ์์ง๋ง as
๋ฅผ ์ฌ์ฉํ ๋ช
์์ ๋ณํ์ ์ง์๋ฉ๋๋ค. ์ด๋ ์ผ๋ฐ์ ์ผ๋ก C ์๋ฏธ๋ก ์ ๋ฐ๋ผ ์ ์๋ฉ๋๋ค.
fn main() { let value: i64 = 1000; println!("as u16: {}", value as u16); println!("as i16: {}", value as i16); println!("as u8: {}", value as u8); }
as
์ ๊ฒฐ๊ณผ๋ Rust์์ ํญ์ ์ ์๋๋ฉฐ ์ฌ๋ฌ ํ๋ซํผ์์ ์ผ๊ด๋ฉ๋๋ค. ์ด๋ ๊ธฐํธ๋ฅผ ๋ณ๊ฒฝํ๊ฑฐ๋ ๋ ์์ ํ์
์ผ๋ก ๋ณํํ ๋์ ์ง๊ด๊ณผ ์ผ์นํ์ง ์์ ์ ์์ต๋๋ค. ๋ฌธ์๋ฅผ ํ์ธํ๊ณ ๋ช
ํํ๊ฒ ์ค๋ช
ํด ์ฃผ์ธ์.
Casting with as
is a relatively sharp tool that is easy to use incorrectly, and can be a source of subtle bugs as future maintenance work changes the types that are used or the ranges of values in types. Casts are best used only when the intent is to indicate unconditional truncation (e.g. selecting the bottom 32 bits of a u64
with as u32
, regardless of what was in the high bits).
For infallible casts (e.g. u32
to u64
), prefer using From
or Into
over as
to confirm that the cast is in fact infallible. For fallible casts, TryFrom
and TryInto
are available when you want to handle casts that fit differently from those that donโt.
์ด ์ฌ๋ผ์ด๋๊ฐ ๋๋ ํ ์ ์ ์ฌ์ด๊ฐ๋ ๊ฒ์ด ์ข์ต๋๋ค.
as
is similar to a C++ static cast. Use of as
in cases where data might be lost is generally discouraged, or at least deserves an explanatory comment.
์ด๋ ์ ์๋ฅผ usize
๋ก ๋ณํํ์ฌ ์์ธ์ผ๋ก ์ฌ์ฉํ ๋ ์ผ๋ฐ์ ์
๋๋ค.