Welcome to our Rust tutorial on integer types! In this lesson, we'll dive into the world of numerical data types in Rust, focusing on the integral types like i32, u32, and more. By the end of this lesson, you'll have a solid understanding of how to work with these types in your Rust projects. 📝
In programming, integer types are used to represent whole numbers (no decimal points). Rust provides several built-in integer types, including signed and unsigned varieties.
Signed integer types can represent both positive and negative numbers. Rust provides the following signed integer types:
i8: Signed 8-bit integer, ranging from -128 to 127.i16: Signed 16-bit integer, ranging from -32768 to 32767.i32: Signed 32-bit integer, ranging from -2147483648 to 2147483647.i64: Signed 64-bit integer, ranging from -9223372036854775808 to 9223372036854775807.isize: Signed integer type that matches the architecture's pointer size.Unsigned integer types can represent only positive numbers and zero. Rust provides the following unsigned integer types:
u8: Unsigned 8-bit integer, ranging from 0 to 255.u16: Unsigned 16-bit integer, ranging from 0 to 65535.u32: Unsigned 32-bit integer, ranging from 0 to 4294967295.u64: Unsigned 64-bit integer, ranging from 0 to 18446744073709551615.usize: Unsigned integer type that matches the architecture's pointer size.Let's take a look at a simple example that demonstrates how to work with integer types in Rust.
fn main() {
let x: i32 = 42;
let y: u32 = 10;
let sum: u32 = x as u32 + y;
println!("The sum is: {}", sum);
}In this example, we've declared two variables x and y of types i32 and u32, respectively. We then convert x to a u32 so we can perform addition with y. Finally, we print the result.
Which Rust integer type has the largest range?
That's it for our deep dive into Rust's integer types! In the next lesson, we'll explore Rust's floating-point types. Stay tuned! 🎯