Day #4 of Rust 100 Days Challenge:  Data Types

Day #4 of Rust 100 Days Challenge: Data Types

I'm excited to share my progress on Day 4 of my 100 Days of Rust challenge. Today, I explored Rust's data types in depth. Here's a summary of what I learned, along with some code examples.

Scalar Data Types

Rust has four primary scalar data types: integers, floating-point numbers, booleans, and characters. These types are the building blocks for more complex data structures.

Number Formats and Postfix Types

Numbers in Rust can be written in various formats:

- Decimal: 98_222

- Hexadecimal: 0xff

- Octal: 0o77

- Binary: 0b1111_0000

- Byte (u8 only): b'A'

You can also specify the type of a number using postfix annotations:

- 3.4f32 for a 32-bit floating-point number

- 3u32 for a 32-bit unsigned integer

- 10i8 for an 8-bit signed integer

Memory Consumption and Operations

Understanding how much memory each type consumes is crucial for writing efficient programs:

- i8 and u8 use 1 byte

- i16 and u16 use 2 bytes

- i32 and u32 use 4 bytes

- i64 and u64 use 8 bytes

- i128 and u128 use 16 bytes

- f32 uses 4 bytes

- f64 uses 8 bytes

Rust allows various operations on scalar types, such as arithmetic, logical, and comparison operations.

Example:

fn main() {

let integer: i32 = 42;

let float: f64 = 3.14;

let boolean: bool = true;

let character: char = 'R';

println!("Integer: {}", integer);

println!("Float: {}", float);

println!("Boolean: {}", boolean);

println!("Character: {}", character);

let hex: u32 = 0xff;

let octal: u32 = 0o77;

let binary: u32 = 0b1111_0000;

println!("Hex: {}, Octal: {}, Binary: {}", hex, octal, binary);

let typed_float: f32 = 3.4f32;

println!("Typed Float: {}", typed_float);

}

Compound Data Types

Rust also has two primary compound data types: tuples and arrays.

Tuples

Tuples can group values of different types into a single compound type. You can access elements using pattern matching or indexing.

Arrays

Arrays are collections of elements of the same type. The length of an array is fixed.

Example:

fn main() {

let tuple: (i32, f64, char) = (42, 3.14, 'R');

let (x, y, z) = tuple;

println!("Tuple values: {}, {}, {}", x, y, z);

println!("Tuple values: {}, {}, {}", tuple.0, tuple.1, tuple.2);

let array: [i32; 3] = [1, 2, 3];

println!("Array values: {:?}", array);

}

Today was a productive day learning about Rust's scalar and compound data types. These fundamental concepts are essential for writing efficient and safe Rust code. I look forward to continuing my journey and sharing more insights as I progress.

Stay tuned for more updates on my 100 Days of Rust challenge!

Congrats, Rashid Iqbal! Amazing progress! Keep pushing forward, we're cheering you on!??

回复

要查看或添加评论,请登录

社区洞察

其他会员也浏览了