In the realm of Rust, data types are the magical elements that breathe life into your code. They define the nature of the data that can be stored and manipulated, each with its own unique properties and abilities. This blog post will take you on a journey through the mystical world of Rust data types, including integers, floating-point numbers, booleans, characters, strings, arrays, tuples, slices, and structs.
Integers and Floating-Point Numbers: The Elemental Forces
Integers and floating-point numbers are the elemental forces in the world of Rust. Integers, whole numbers without a fractional component, can be either signed (i8, i16, i32, i64, i128, isize) or unsigned (u8, u16, u32, u64, u128, usize). The number following the i or u indicates the number of bits the integer occupies in memory.
Floating-point numbers in Rust are numbers with a fractional component. They can be single-precision (f32) or double-precision (f64).
let x: i32 = 5;
let y: f64 = 3.14;
Booleans and Characters: Truth and Expression
Booleans in Rust are binary data types. They can be either true or false.
Characters in Rust are Unicode scalar values. They’re represented with the char keyword and are 4 bytes in size.
let t: bool = true;
let c: char = 'z';
Strings, Arrays, and Tuples: Language, Collections, and Diversity
Strings in Rust are a collection of characters. They’re represented with the String keyword.
Arrays in Rust are a collection of multiple values of the same type. The size of the array is known at compile time.
Tuples in Rust are a collection of multiple values of different types. The size of the tuple is known at compile time.
let s: String = "hello".to_string();
let a: [i32; 3] = [1, 2, 3];
let t: (i32, f64, char) = (500, 6.4, 'j');
Slices and Structs: References and Customization
Slices in Rust are a reference to a contiguous sequence of elements in an array.
Structs in Rust are custom data types that let you name and package together multiple related values.
let a = [1, 2, 3, 4, 5];
let slice = &a[1..3];
struct Color {
red: u8,
green: u8,
blue: u8,
}
let black = Color { red: 0, green: 0, blue: 0 };
Conclusion
Well, I may have played too much DND to cut down on DND, I’m now full of elf priests using two-handed axes.
