Day 5: An Introduction to Rust’s Data Types – Building Blocks of Safe Code

Venkat Annangi
Venkat Annangi
23/09/2024 13:51 4 min read 59 views
#rust #108 days of rust

In Day 5 of 108 Days of Rust, we introduce the essential data types available in Rust. Rust is a statically typed language with scalar and compound types, including strings, vectors, and more. We’ll introduce these key data types today and dive deeper into each in the following days.

Rust’s Type System

Rust’s type system ensures memory safety and efficiency. Rust is a statically typed language, meaning every variable must have a known type at compile time. The main categories of data types in Rust are:

  1. Scalar Types – Single value data types.
  2. Compound Types – Types that can group multiple values.

1. Scalar Types

Scalar types represent a single value. Rust has four primary scalar types:

a. Integers

Integers are whole numbers. Rust provides both signed and unsigned integers in various sizes. Choose the appropriate size based on the range you need.

  • Signed: i8, i16, i32, i64, i128
  • Unsigned: u8, u16, u32, u64, u128
let x: i32 = 42;  // Signed integer
let y: u8 = 255;  // Unsigned integer

b. Floating-Point Numbers

Rust supports two types of floating-point numbers:

  • f32: 32-bit floating point.
  • f64: 64-bit floating point (default).
let pi: f64 = 3.14159;
let half: f32 = 0.5;

c. Booleans

Booleans represent a value of true or false. They are used in control flow to make decisions.

let is_active: bool = true;

d. Characters

The char type in Rust represents a single character. It can store any Unicode scalar value, not just ASCII.

let letter: char = 'R';
let heart: char = '❤';

2. Compound Types

Compound types can group multiple values into one type. Rust has a few key compound types:

a. Tuples

A tuple groups values of different types. Once declared, the length and types of a tuple cannot change.

let person: (i32, f64, bool) = (30, 5.8, true);

b. Arrays

An array is a fixed-size list of elements of the same type. Arrays are useful when you know the number of elements and they won’t change.

let numbers: [i32; 3] = [1, 2, 3];  // An array of 3 integers

c. Vectors

Unlike arrays, vectors (Vec<T>) can grow and shrink in size dynamically. They are the go-to data type for collections where the size might change.

let mut numbers = vec![1, 2, 3]; // A vector of integers
numbers.push(4);  // Add another element

3. Strings in Rust

Strings are an essential data type in Rust and come in two forms:

  1. String slices (&str): Immutable references to a string.
  2. String: A growable, heap-allocated string.
let greeting = "Hello, world!"; // String slice
let mut name = String::from("Rust");
name.push_str(" is awesome!"); // Modifying the string

4. Other Data Types

a. Option Type

Rust’s Option type is used when a value can either be present (Some) or absent (None). It’s a safer alternative to null values found in other languages.

let some_number: Option<i32> = Some(5);
let absent_number: Option<i32> = None;

b. Result Type

The Result type is used for error handling. A function that can fail will return either Ok(value) or Err(error).

use std::fs::File;

fn main() {
    let file_result = File::open("hello.txt");

    match file_result {
        Ok(file) => println!("File opened successfully!"),
        Err(error) => println!("Problem opening file: {:?}", error),
    }
}

5. Type Inference and Type Annotations

Rust is capable of type inference, meaning it can often figure out the type of a variable based on its value. However, you can also provide type annotations explicitly when needed.

Example of Inference:

let count = 42;  // Rust infers this is an i32

Example with Explicit Annotations:

let count: u32 = 42; // Explicitly declare count as an unsigned 32-bit integer

Conclusion

In today’s post, we introduced Rust’s primary data types: integers, floating-point numbers, booleans, characters, strings, arrays, tuples, vectors, and more. These data types are the building blocks of Rust programs. In the coming days, we’ll dive deep into each type and explore how they work in more detail.

What’s Next:

  • Day 6: Mastering Integers in Rust: A deep dive into Rust’s integer types and overflow handling.
  • Day 7: Floating-Point Numbers in Rust: Explore how to handle floating-point numbers with precision.
  • Day 8: Working with Strings: Learn about the differences between String and &str, and how to manipulate strings.
  • Day 9: Understanding Vectors in Rust: Discover how to use Rust’s flexible, growable arrays.

Comments