Rust Print Output

‮ww‬w.theitroad.com

In Rust, you can print output to the console using the println! macro. The println! macro works similarly to printf in C and other languages, but with some differences due to Rust's ownership and borrowing system.

Here's an example of how to use the println! macro to print a string to the console:

fn main() {
    let name = "Alice";
    println!("Hello, {}!", name);
}

In this example, we define a variable name with the value "Alice". We then use the println! macro to print the string "Hello, Alice!" to the console.

You can also use formatting syntax in the println! macro to insert values into a string. For example:

fn main() {
    let name = "Alice";
    let age = 30;
    println!("{} is {} years old.", name, age);
}

In this example, we use {} as a placeholder for the values of the name and age variables. The values are inserted into the string in the order they appear in the argument list.

You can also use named arguments to specify the order in which the values should be inserted:

fn main() {
    let name = "Alice";
    let age = 30;
    println!("{name} is {age} years old.", name=name, age=age);
}

In this example, we use the name= and age= syntax to specify the names of the arguments, which allows us to use them in any order we want.