English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Rust Output to Command Line

Before we officially learn the Rust language, we need to first learn how to output a piece of text to the command line, which is almost a必备 skill before learning every language, because outputting to the command line is almost the only way to express the result of a program during the language learning phase.

In the previous Hello, World program, it was roughly explained how to output a string, but it was not comprehensive. You may be puzzled why there is an exclamation mark (!) after println in println!("Hello World"). Does this mean that an exclamation mark must be added after every Rust function? Clearly, that is not the case. println is not a function, but a macro rule. There is no need to delve deeper into what a macro rule is; it will be introduced in a dedicated chapter later, and it will not affect the next section of learning.

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

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

The output result of the above program is:

a is 12

If I want to output a twice, then I need to write it as:

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);

You can put a number between {} to treat the following variable arguments as an array, starting from index 0.

If you want to output { or } What should we do? In the format string, you can use {{ and }} Escape characters for { and } are used. But other commonly used escape characters are similar to those in C, all starting with a backslash.

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

The output result of the above program is:

{}