Variables and Mutability in Rust Cheat Sheet

Rust is a modern programming language that is gaining popularity due to its performance and safety. It features powerful type-checking mechanisms that prevent common errors like null-pointer exceptions and dangling pointers. One important aspect of Rust’s type system is its set of primitive data types, which form the building blocks of rust hacks more complex data structures. In this article, we’ll present a cheat sheet of Rust’s primitive data types, along with examples of how to use them.

1. Integer Types

Rust has four integer types: i8, i16, i32, and i64 (signed), and u8, u16, u32, and u64 (unsigned). The number after ‘i’ or ‘u’ specifies the number of bits the integer type occupies (e.g. i8 is 8 bits, u16 is 16 bits, etc.). The signed integer types represent both negative and positive numbers, while the unsigned integer types represent only positive numbers. The usize and isize types are also integer types, but their size depends on the architecture of the system (32-bit or 64-bit).

Here’s an example of using integer types in Rust:

    let a: i32 = 42;

    let b: u8 = 255;

    let c: isize = -123;

2. Floating-Point Types

Rust has two floating-point types: f32 and f64. The f32 type is a single-precision floating-point number, while the f64 type is a double-precision floating-point number. Floating-point types are used for storing numbers with fractional parts, like pi or the square root of 2.

Here’s an example of using floating-point types in Rust:

    let a: f32 = 3.14;

    let b: f64 = 2.71828;

3. Boolean Type

Rust has a boolean type, bool, which can either be true or false. Boolean types are often used in conditional statements and loops.

Here’s an example of using a boolean type in Rust:

    let a: bool = true;

    let b: bool = false;

4. Character Type

Rust has a character type, char, which represents a single Unicode scalar value. This type is used for storing characters, like ‘a’, ‘b’, ‘c’, etc.

Here’s an example of using a character type in Rust:

    let a: char = ‘a’;

    let b: char = ‘🚀’;

5. Unit Type

Rust has a unit type, (), which represents an empty tuple. This type is used when a function or expression doesn’t need to return a value. The unit type is useful for indicating the absence of a value or a side effect.

Here’s an example of using a unit type in Rust:

    fn print_hello() {

        println!(“Hello, world!”);

    }

    let a: () = print_hello();

Understanding Rust’s primitive data types is crucial for writing safe and efficient Rust code. In this article, we’ve covered Rust’s five primitive data types: integer types, floating-point types, boolean type, character type, and unit type. By mastering these types, you’ll be able to create Rust programs that are more robust, readable, and maintainable. We hope this cheat sheet has been helpful, and we encourage you to explore Rust’s type system further. Happy coding!