Start Coding

Rust Data Types

Rust is a statically-typed language, which means that it must know the types of all variables at compile time. The compiler can usually infer what type we want to use based on the value and how we use it. However, in cases when many types are possible, we must add a type annotation.

Scalar Types

Rust has four primary scalar types: integers, floating-point numbers, booleans, and characters.

Integers

An integer is a number without a fractional component. Rust provides several integer types with different sizes:

  • 8-bit: i8, u8
  • 16-bit: i16, u16
  • 32-bit: i32, u32
  • 64-bit: i64, u64
  • 128-bit: i128, u128
  • arch: isize, usize (depends on the architecture of the computer)

The prefix 'i' denotes signed integers, while 'u' denotes unsigned integers.

let x: i32 = 42;
let y: u64 = 100_000;

Floating-Point Numbers

Rust has two floating-point types: f32 and f64. The default type is f64 because on modern CPUs, it's roughly the same speed as f32 but is capable of more precision.

let x = 2.0; // f64
let y: f32 = 3.0; // f32

Booleans

The boolean type in Rust has two possible values: true and false. Booleans are one byte in size.

let t = true;
let f: bool = false;

Characters

Rust's char type represents a Unicode Scalar Value, which means it can represent a lot more than just ASCII. Char literals are specified with single quotes.

let c = 'z';
let z: char = 'ℤ';
let heart_eyed_cat = '😻';

Compound Types

Compound types can group multiple values into one type. Rust has two primitive compound types: tuples and arrays.

Tuples

A tuple is a general way of grouping together a number of values with a variety of types into one compound type.

let tup: (i32, f64, u8) = (500, 6.4, 1);
let (x, y, z) = tup; // Destructuring
println!("The value of y is: {}", y);

Arrays

Unlike a tuple, every element of an array must have the same type. Arrays in Rust have a fixed length.

let a = [1, 2, 3, 4, 5];
let first = a[0];
let second = a[1];

Important Considerations

  • Rust's type system and ownership rules guarantee memory safety without needing a garbage collector.
  • Type annotations are usually not necessary due to Rust's type inference, but they can be helpful for clarity.
  • Be aware of potential integer overflow when working with fixed-size integer types.
  • Use Rust Vectors when you need a growable array-like data structure.

Understanding Rust's data types is crucial for writing efficient and safe code. They form the foundation for more complex concepts like Rust's Ownership Concept and Rust's Borrowing Rules.