Simple Data Types

Rust by example - Primitives

Type FamilyTypesExamples
Signed Integersi8⮳, i16⮳, i32⮳, i64⮳, i128⮳, isize⮳.-8i8, -32i32.
Unsigned Integersu8⮳, u16⮳, u32⮳, u64⮳, u128⮳, usize⮳.6u8.
Floating pointf32⮳, f64⮳.0.15.
Booleanbool⮳.true, false.
Unicode Charactercharlet z: char = 'ℤ';
Unitunit⮳.The () type (aka void in other languages) has exactly one value (), and is used when there is no other meaningful value that could be returned.
Nevernever⮳.! represents the type of computations which never resolve to any value at all. For example, the exit function fn exit(code: i32) -> ! exits the process without ever returning, and so returns !.

usize⮳ and isize⮳ are 32 or 64 bits, depending on the architecture of the computer.

// COMING SOON

Composite Types

TypeExamples
Tupleslet tup: (i32, f64, u8) = (500, 6.4, 1);. Access via let five_hundred = x.0;. Destructuring via let (x, y, z) = tup;.
Arrayslet a: [i32; 5] = [1, 2, 3, 4, 5]; allocated on the stack. Access via let first = a[0];.

A Vector is a similar collection type provided by the standard library that is allowed to grow or shrink in size.

See also:

  • Enums.
    • Option.
    • Result.
  • Slices.
  • Strings.
  • Structs.
  • Vectors.

Type Aliases

Use the type keyword to declare type aliases: type Kilometers = i32;.

Handle Overflows

  • Wrap in all modes with the wrapping_* methods, such as wrapping_add⮳.
  • Return the std::option::Option::None⮳ value if there is overflow with the checked_* methods.
  • Return the value and a boolean indicating whether there was overflow with the overflowing_* methods.
  • Saturate at the value's minimum or maximum values with the saturating_* methods.

Related Topics

  • Data Structures