DEV Community

Cover image for 🚀 Rust Basics 2: Data Types, Shadowing, and String Manipulation 🦀
RealACJoshua
RealACJoshua

Posted on • Edited on

2

🚀 Rust Basics 2: Data Types, Shadowing, and String Manipulation 🦀

Welcome back to our RUST BASICS series! In this post, we’ll explore data types, shadowing, and string manipulation in Rust. These concepts will help you understand how Rust handles values and strings efficiently.


Step 1: Understanding Data Types

Rust is a statically-typed language, which means every variable must have a type. Rust can infer types for you, but sometimes it’s useful to specify them explicitly.

Primitive Types in Rust:

  1. Integer: i8, i16, i32, i64, i128 (signed), and u8, u16, u32, u64, u128 (unsigned).

  2. Floating-point: f32 and f64.

  3. Boolean: bool (true or false).

  4. Character: char (single characters like 'a' or '#').

Example Code:

fn main() {
    let age: i32 = 25;       // Integer
    let height: f64 = 5.9;   // Floating-point
    let is_student: bool = true; // Boolean
    let grade: char = 'A';   // Character

    println!("Age: {}", age);
    println!("Height: {} ft", height);
    println!("Is Student: {}", is_student);
    println!("Grade: {}", grade);
}

Enter fullscreen mode Exit fullscreen mode

Step 2: Constants vs Variables

Constants are immutable and must have a type specified. They’re declared with the const keyword and are accessible globally.

Variables (declared with let) can be mutable if prefixed with mut.

Example Code:

const PI: f64 = 3.14159; // Constant
fn main() {
    let mut counter = 0; // Mutable variable
    println!("Counter: {}", counter);

    counter += 1; // Increment counter
    println!("Updated Counter: {}", counter);

    println!("Value of PI: {}", PI);
}

Enter fullscreen mode Exit fullscreen mode

Step 3: Shadowing

Shadowing allows you to redefine a variable with the same name. This is useful when you want to transform data without changing its name.

Example Code:

fn main() {
    let number = 5;
    println!("Number: {}", number);

    let number = number + 1; // Shadowing
    println!("Shadowed Number: {}", number);

    let number = "Five"; // Shadowing with a different type
    println!("Number as a string: {}", number);
}
Enter fullscreen mode Exit fullscreen mode

Note: Shadowing creates a new variable and doesn’t modify the previous one. This is different from using mut.


Step 4: String Manipulation

Rust has two types of strings:

  1. String slices (&str): Immutable references to string data.

  2. String: A growable, heap-allocated data structure.

Example Code:

fn main() {
    let greeting = "Hello"; // &str
    let mut name = String::from("TheACJ"); // String

    println!("Greeting: {}", greeting);
    println!("Name: {}", name);

    // Modify the String
    name.push_str(" Rustacean!");
    println!("Updated Name: {}", name);
}

Enter fullscreen mode Exit fullscreen mode

String Methods:

fn main() {
    let name = String::from("Rustacean");
    println!("Length: {}", name.len());           // Get length
    println!("Is Empty: {}", name.is_empty());    // Check if empty
    println!("Uppercase: {}", name.to_uppercase()); // Convert to uppercase
}

Enter fullscreen mode Exit fullscreen mode

Step 5: Practice Challenges

A. Modify the program to calculate the area of a circle:

const PI: f64 = 3.14159;
fn main() {
    let radius: f64 = 7.0;
    let area = PI * radius * radius;
    println!("The area of the circle is: {}", area);
}
Enter fullscreen mode Exit fullscreen mode

B. Write a program to count the number of characters in a user-inputted string:

use std::io;

fn main() {
    let mut input = String::new();
    println!("Enter a string:");

    io::stdin()
        .read_line(&mut input)
        .expect("Failed to read input");

    let trimmed = input.trim();
    println!("The string '{}' has {} characters.", trimmed, trimmed.len());
}
Enter fullscreen mode Exit fullscreen mode

Troubleshooting Tips

If you get a type mismatch error, ensure variable types are consistent.

If you see cannot borrow as mutable, check if your variable is declared as mut.


🎉 That’s it for RUST BASICS 2! You’ve learned about data types, constants, shadowing, and string manipulation. In the next post, we’ll cover control flow and loops in Rust.


Feel free to share your solutions or ask questions in the comments. Happy coding! 🦀

Check out the Rust Documentation for more details.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more