Rust Data Types

Rust is a statically typed programming language, which means the type of a variable must be known at compile time. Rust’s data types are divided into two main categories: scalar and compound.

What Are Data Types in Rust?

A data type defines the kind of data a variable can hold, such as integers, floating-point numbers, characters, or boolean values. Rust enforces type safety, ensuring that you cannot use variables in ways that are not allowed for their type.

Scalar Types

Scalar types represent single values. Rust has four primary scalar types:

  1. Integer Types
  2. Floating-Point Types
  3. Boolean Type
  4. Character Type

1. Integer Types

Integers are whole numbers without fractional components. They can be signed (i) or unsigned (u), with various sizes depending on the number of bits.

LengthSigned (i)Unsigned (u)
8-biti8u8
16-biti16u16
32-biti32u32
64-biti64u64
128-biti128u128
archisizeusize
  • Signed integers can store both positive and negative numbers.
  • Unsigned integers store only positive numbers.

Example: Integer Types

fn main() {
let signed: i32 = -50;
let unsigned: u32 = 50;
println!("Signed: {}, Unsigned: {}", signed, unsigned);
}

2. Floating-Point Types

Floating-point types represent numbers with decimal points. Rust supports:

  • f32 (32-bit, single precision)
  • f64 (64-bit, double precision, default type)

Example: Floating-Point Types

fn main() {
let pi: f64 = 3.14159;
let e: f32 = 2.718;
println!("Pi: {}, Euler's Number: {}", pi, e);
}

3. Boolean Type

The bool type represents a value that can either be true or false.

Example: Boolean Type

fn main() {
let is_rust_fun: bool = true;
println!("Is Rust fun? {}", is_rust_fun);
}

4. Character Type

The char type represents a single Unicode character. Each character is enclosed in single quotes ( ‘ ).

Example: Character Type

fn main() {
let letter: char = 'R';
let emoji: char = 'šŸ˜Š';
println!("Letter: {}, Emoji: {}", letter, emoji);
}

Compound Types

Compound types can group multiple values into one type. Rust has two compound types:

  1. Tuples
  2. Arrays

1. Tuples

A tuple groups values of different types into one compound type. Tuples have a fixed size and their values can be accessed using indexing.

Example: Tuples

fn main() {
let person: (&str, i32, f64) = ("Alice", 30, 5.6);
println!("Name: {}, Age: {}, Height: {}", person.0, person.1, person.2);
}

You can also destructure tuples to access individual elements:

fn main() {
let person = ("Bob", 25, 6.1);
let (name, age, height) = person;
println!("Name: {}, Age: {}, Height: {}", name, age, height);
}

2. Arrays

An array is a collection of values of the same type with a fixed length.

Example: Arrays

fn main() {
let numbers: [i32; 5] = [1, 2, 3, 4, 5]; // Fixed-length array
println!("First number: {}", numbers[0]);
}

Rust also allows initializing an array with the same value for all elements:

fn main() {
let zeros = [0; 10]; // Array of 10 zeros
println!("Array: {:?}", zeros);
}

Special Types

  1. The Unit Type ()
    • Represents an empty value or no value at all.
    • Often used as the return type of functions that donā€™t return any value.
  2. Slices
    • Slices allow accessing a portion of an array or a string without copying.
fn main() {
let arr = [1, 2, 3, 4, 5];
let slice = &arr[1..4];
println!("Slice: {:?}", slice);
}

Type Inference

Rust can infer the type of a variable based on the value assigned to it. However, you can also specify types explicitly to avoid ambiguity.

Example: Type Inference

fn main() {
let x = 10; // Inferred as i32
let y = 3.14; // Inferred as f64
println!("x: {}, y: {}", x, y);
}

Common Errors

  1. Type Mismatch:
    • Error: mismatched types.
    • Solution: Ensure the type of value matches the variable’s type.
  2. Index Out of Bounds:
    • Error: index out of bounds.
    • Solution: Always access valid indices in arrays.

Exercises

  1. Create a program that uses a tuple to store and display details about a book.
  2. Write a program that creates an array of integers and finds their sum.
  3. Experiment with slices to extract parts of an array.

Leave a Comment

BoxofLearn