Rust類型轉換 - 彆名
Rust類型轉換 - 彆名
type語句聲明可以以現有類型被用來給一個新的名字。類型必須有 CamelCase
名稱, 或者編譯器會提出警告。例外(異常)是原始類型: usize
,f32
, 等.
// `NanoSecond` is a new name for `u64`. type NanoSecond = u64; type Inch = u64; // Use an attribute to silence warning. #[allow(non_camel_case_types)] type u64_t = u64; // TODO ^ Try removing the attribute // Use an attribute to silence warnings #[allow(trivial_numeric_casts)] fn main() { // `NanoSecond` = `Inch` = `u64_t` = `u64`. let nanoseconds: NanoSecond = 5 as u64_t; let inches: Inch = 2 as u64_t; // Note that type aliases *don't* provide any extra type safety, because // aliases are *not* new types println!("{} nanoseconds + {} inches = {} unit?", nanoseconds, inches, nanoseconds + inches); }
使用彆名主要是減少輸入;例如 IoResult<T> 是類型Result<T, IoError> 的彆名.