Rust Println
# Rust Output to Command Line
Before formally learning the Rust language, we need to first learn how to output text to the command line. This is almost an essential skill before learning any programming language, as outputting to the command line is almost the only way for programs to express results during the language learning stage.
The previous "Hello, World" program probably already showed everyone how to output a string, but it wasn't comprehensive. Everyone might be confused why there is an exclamation mark `!` after `println` in `println!("Hello World")`. Does every Rust function need to have an exclamation mark added after it? Obviously not. `println` is not a function, but a macro rule. There's no need to dig deeper into what macro rules are here; they will be introduced in later chapters and won't affect the next part of our learning.
There are two main ways to output text in Rust: `println!()` and `print!()`. Both of these "functions" are methods to output strings to the command line. The only difference is that the former appends a newline character at the end of the output. When using these "functions" to output information, the first parameter is a format string, followed by a variable number of arguments that correspond to the "placeholders" in the format string. This is very similar to the `printf` function in the C language. However, the placeholders in Rust's format strings are not in the form of **"% + letter"**, but rather a pair of **{}**.
## Example: .rs File
fn main(){
let a =12;
println!("a is {}", a);
}
Compile the .rs file using the `rustc` command:
$ rustc .rs # Compile .rs file
After compilation, it will generate the **** executable file:
$ ./ # Execute
The output of the above program is:
a is 12
If I want to output `a` twice, wouldn't I have to write it like this:
println!("a is {}, a again is {}", a, a);
Actually, there's a better way to write it:
println!("a is {0}, a again is {0}", a);
You can place a number between the `{}`. It will treat the subsequent variable arguments as an array to access, with the index starting from 0.
What if you want to output **{** or **}**? In the format string, **{{** and **}}** are used to escape and represent `{` and `}` respectively. However, other common escape characters are the same as in C, starting with a backslash.
fn main() { println!("{{}}"); }
The output of the above program is:
{}
YouTip