基本类型

Rust 提供了对各种基本类型的访问。一个例子包括

标量类型

  • 有符号整数:i8i16i32i64i128isize(指针大小)
  • 无符号整数:u8u16u32u64u128usize(指针大小)
  • 浮点数:f32f64
  • char Unicode 标量值,例如 'a''α''∞' (每个 4 字节)
  • bool 要么 true 要么 false
  • 单元类型 (),其唯一可能的值是一个空元组:()

尽管单元类型的值是一个元组,但它不被认为是复合类型,因为它不包含多个值。

复合类型

  • 数组,例如 [1, 2, 3]
  • 元组,例如 (1, true)

变量始终可以进行类型注解。数字还可以通过后缀默认进行注解。整数默认为 i32,浮点数默认为 f64。请注意,Rust 也可以从上下文中推断类型。

fn main() {
    // Variables can be type annotated.
    let logical: bool = true;

    let a_float: f64 = 1.0;  // Regular annotation
    let an_integer   = 5i32; // Suffix annotation

    // Or a default will be used.
    let default_float   = 3.0; // `f64`
    let default_integer = 7;   // `i32`

    // A type can also be inferred from context.
    let mut inferred_type = 12; // Type i64 is inferred from another line.
    inferred_type = 4294967296i64;

    // A mutable variable's value can be changed.
    let mut mutable = 12; // Mutable `i32`
    mutable = 21;

    // Error! The type of a variable can't be changed.
    mutable = true;

    // Variables can be overwritten with shadowing.
    let mutable = true;

    /* Compound types - Array and Tuple */

    // Array signature consists of Type T and length as [T; length].
    let my_array: [i32; 5] = [1, 2, 3, 4, 5];

    // Tuple is a collection of values of different types 
    // and is constructed using parentheses ().
    let my_tuple = (5u32, 1u8, true, -5.04f32);
}

另请参阅

stdmutinferenceshadowing