Easy Tutorial
❮ Rust Slice Rust Basic Syntax ❯

Rust Output to Command Line

Before formally learning the Rust language, we need to first understand how to output text to the command line. This is a fundamental skill almost essential before learning any language, as outputting to the command line is the primary method of expressing results during the language learning phase.

In the previous Hello, World program, you might have been introduced to the method of outputting strings, but it wasn't comprehensive. You might be wondering why there is an exclamation mark ! after println!("Hello World"). Does this mean every function in Rust is followed by an exclamation mark? Clearly, that's not the case. println is not a function but a macro. There's no need to delve deeper into what a macro is; it will be covered in later chapters and does not affect the upcoming learning.

There are mainly two ways to output text in Rust: println!() and print!(). Both "functions" are methods to output strings to the command line, with the only difference being that the former appends a newline character at the end of the output. When using these "functions" to output information, the first argument is the format string, followed by a series of variable arguments corresponding to the "placeholders" in the format string, similar to the printf function in C. However, the placeholders in Rust's format string are not in the form of "% + letter" but are represented by {}.

Example: tutorialpro.rs File

fn main() { 
    let a = 12; 
    println!("a is {}", a); 
}

Compile the tutorialpro.rs file using the rustc command:

$ rustc tutorialpro.rs   # Compile the tutorialpro.rs file

After compilation, an executable file named tutorialpro will be generated:

$ ./tutorialpro    # Execute tutorialpro

The output of the above program is:

a is 12

If you want to output a twice, you might think you need to write:

println!("a is {}, a again is {}", a, a);

However, there's a better way:

println!("a is {0}, a again is {0}", a);

Inside the {}, you can place a number, which will treat the subsequent variable arguments as an array, with indices starting from 0.

What if you want to output { or }? In the format string, {{ and } are used to escape { and }, respectively. Other common escape characters are the same as in C, starting with a backslash.

fn main() { 
    println!("{{}}"); 
}

The output of the above program is:

{}
❮ Rust Slice Rust Basic Syntax ❯