Rust Data Types

www.igift‮moc.aedi‬

Rust is a statically-typed language, which means that the types of variables are known at compile time. Rust provides several built-in data types, including primitive types and compound types.

Primitive types are the most basic data types in Rust. They include:

  • bool: a boolean type that can be either true or false.
  • char: a Unicode scalar value that represents a single character.
  • Numeric types:
      - i8, i16, i32, i64, i128: signed integers with different sizes.
    • u8, u16, u32, u64, u128: unsigned integers with different sizes.
    • f32, f64: floating-point numbers with single and double precision.
Compound types are types that are composed of other types. They include:
  • Arrays: fixed-size collections of elements of the same type. Arrays in Rust have a fixed size and cannot grow or shrink at runtime.
  • Tuples: ordered collections of elements of different types. Tuples can contain any number of elements and can have elements of different types.
  • Structs: custom data types that allow you to define your own data structures. Structs can contain multiple named fields of different types.

Rust also has the Option and Result types, which are used to handle errors and missing values. The Option type represents either Some value or None, while the Result type represents either Ok value or Err value.

You can use these data types to define variables in Rust. For example:

let is_valid: bool = true;
let my_char: char = 'a';
let my_array: [i32; 3] = [1, 2, 3];
let my_tuple: (i32, f64, char) = (42, 3.14, 'x');

struct Person {
    name: String,
    age: u32,
}

let alice = Person {
    name: String::from("Alice"),
    age: 30,
};

In this example, we define variables of different data types, including bool, char, array, tuple, and struct. We specify the type of each variable using a colon and the type name after the variable name.