Rust Data Types

Rust Tutorial

🦀 Rust Data Types

Rust Data Types is a statically typed language, which means every variable has a known type at compile time. Rust data types are broadly divided into Scalar and Compound types.

🔹 1. Scalar Data Types

Scalar types represent single values.

▶️ Integer Types

Type Size Example
i8 / u8 8-bit let a: i8 = -10;
i16 / u16 16-bit
i32 / u32 32-bit (default) let b = 20;
i64 / u64 64-bit
i128 / u128 128-bit
isize / usize arch dependent
let x: i32 = 100;
let y: u8 = 255;

▶️ Floating-Point Types

Type Size
f32 32-bit
f64 64-bit (default)
let pi: f64 = 3.14159;

▶️ Boolean Type

let is_rust_fun: bool = true;

▶️ Character Type

let ch: char = 'A';
let emoji: char = '😄';

✔ Rust char is 4 bytes (Unicode).


🔹 2. Compound Data Types

Compound types group multiple values into one type.


▶️ Tuple

Fixed-size collection of different data types.

let person: (&str, i32, bool) = ("Sanjit", 22, true);
println!("{}", person.0);

Destructuring:

let (name, age, active) = person;

▶️ Array

Fixed-size collection of same data type.

let numbers: [i32; 5] = [1, 2, 3, 4, 5];
println!("{}", numbers[0]);

🔹 3. String Types (Very Important)

▶️ &str (String Slice)

let name = "Rust";
  • Immutable

  • Stored in read-only memory


▶️ String (Heap Allocated)

let mut language = String::from("Rust");
language.push_str(" Programming");

🔹 4. Custom Data Types

▶️ Struct

struct User {
name: String,
age: u32,
}
let user = User {
name: String::from(“Sanjit”),
age: 22,
};

▶️ Enum

enum Status {
Active,
Inactive,
}
let user_status = Status::Active;

🔹 5. Option Type (No Null in Rust)

Rust has no null. Instead:

let data: Option<i32> = Some(10);
// let data: Option<i32> = None;

🔹 6. Result Type (Error Handling)

let result: Result<i32, &str> = Ok(100);
// Err("Error occurred")

🔑 Type Inference Example

let x = 10; // inferred as i32
let y = 2.5; // inferred as f64

🧠 Important Notes

  • Rust prevents invalid memory access

  • No implicit type conversion

  • Use as for explicit casting

  • Safer than C/C++ data handling

You may also like...