Rust Output to Command Line

Before formally learning the Rust language, we need to first learn how to output a piece of text to the command line. This is almost an essential skill before learning any language, because outputting to the command line is almost the only way for programs to express results during the language learning stage.

In the previous Hello, World program, we probably already showed everyone how to output strings, but it is not comprehensive. You may be wondering why after println in println!( "Hello World") there is another!symbol? Is it that every Rust function needs an exclamation mark after it? Obviously not. println is not a function, but a macro rule. There is no need to dig deeper into what a macro rule is; it will be introduced in a later chapter, and it does not affect the upcoming learning.

Rust mainly has two ways to output text:println!()andprint!(). These two "functions" are both methods for outputting 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 two "functions" to output information, the first parameter is a format string, followed by a series of variable parameters, corresponding to the "placeholders" in the format string. This is very similar to the printf function in C language. However, the placeholders in the Rust format string are not"% + letter"in form, but rather a pair of{}。

Example: example.rs file

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

Userustccommand to compile the example.rs file:

$ rustc example.rs   # 编译 example.rs 文件

After compilation, it will generateexamplean executable file:

$ ./example    # 执行 example

The output of the above program is:

a is 12 

If I want to output a twice, wouldn't I have to write:

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

Actually, there is a better way to write it:

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

In{}Between them you can put a number, which will treat the following variable parameters as an array to access, with indices starting from 0.

If you want to output{or}what should you do? In the format string, by{{and}}escaping to represent { and } respectively. But other common escape characters are the same as those in C language, all in the form starting with a backslash.

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

The output of the above program is:

{}
Other Extensions