Rust Tutorials: Integer Types (i32, u32, etc.) 🎯

beginner
16 min

Rust Tutorials: Integer Types (i32, u32, etc.) 🎯

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. 📝

What are Integer Types? 💡

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 💡

Signed integer types can represent both positive and negative numbers. Rust provides the following signed integer types:

  1. i8: Signed 8-bit integer, ranging from -128 to 127.
  2. i16: Signed 16-bit integer, ranging from -32768 to 32767.
  3. i32: Signed 32-bit integer, ranging from -2147483648 to 2147483647.
  4. i64: Signed 64-bit integer, ranging from -9223372036854775808 to 9223372036854775807.
  5. isize: Signed integer type that matches the architecture's pointer size.

Unsigned Integer Types 💡

Unsigned integer types can represent only positive numbers and zero. Rust provides the following unsigned integer types:

  1. u8: Unsigned 8-bit integer, ranging from 0 to 255.
  2. u16: Unsigned 16-bit integer, ranging from 0 to 65535.
  3. u32: Unsigned 32-bit integer, ranging from 0 to 4294967295.
  4. u64: Unsigned 64-bit integer, ranging from 0 to 18446744073709551615.
  5. usize: Unsigned integer type that matches the architecture's pointer size.

Working with Integer Types 💡

Let's take a look at a simple example that demonstrates how to work with integer types in Rust.

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.

Quiz 💡

Quick Quiz
Question 1 of 1

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! 🎯