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.
Rust has four primary scalar types: integers, floating-point numbers, booleans, and characters.
An integer is a number without a fractional component. Rust provides several integer types with different sizes:
The prefix 'i' denotes signed integers, while 'u' denotes unsigned integers.
let x: i32 = 42;
let y: u64 = 100_000;
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
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;
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 can group multiple values into one type. Rust has two primitive compound types: tuples and arrays.
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);
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];
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.