OneBite.Dev - Coding blog in a bite size

Format A String In Rust

Code snippet for how to Format A String In Rust with sample and detail explanation

Rust is a powerful programming language that provides high-level abstractions for memory safety. This article will guide you on how to format a string in Rust, a common programming task that comes with its unique nuances.

Code snippet for Formatting a String in Rust

fn main() {
    let name = "John";
    let age = 20;
    let formatted_string = format!("My name is {} and I am {} years old.", name, age);
    println!("{}",formatted_string);
}

Code Explanation for Formatting a String in Rust

The first step in our code snippet is defining a main function which is the entry point to every Rust program.

fn main() {

The next two lines declare two immutable variables. name is a string that contains the name “John”. age is an integer that contains the number 20.

    let name = "John";
    let age = 20;

The format! macro is then used to create a formatted string. It is similar to println!, but instead of printing the output to the console, it returns a String with the output.

The {} are placeholders in the string, and the format! macro will replace these with the variables provided after the format string, in the order they are provided. So here, the first {} is replaced by name, and the second {} is replaced by age.

    let formatted_string = format!("My name is {} and I am {} years old.", name, age);

Finally, the println! macro is used to print the formatted_string to the console.

    println!("{}",formatted_string);
}

As a result, the program prints out “My name is John and I am 20 years old.”. This demonstrates a simple way to format strings in Rust.

rust