Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Примітиви

Rust надає доступ до широкого різноманіття primitives. До прикладів належать:

Скалярні типи

  • Знакові цілі числа: i8, i16, i32, i64, i128 і isize (розмір вказівника)
  • Беззнакові цілі числа: u8, u16, u32, u64, u128 і usize (розмір вказівника)
  • Числа з рухомою комою: f32, f64
  • 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);
}

Також див.:

бібліотеку std, mut, inference і shadowing