Rust Command-Line Output
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 language, because outputting to the command line is nearly the only way for programs to express results during the language-learning stage.
The earlier Hello, World program roughly showed everyone how to output a string, but not comprehensively. You might wonder why in println!( "Hello World") there's a ! symbol after println—do all Rust functions need an exclamation mark? Obviously not. println is not a function, but a macro rule. There's no need to dig deeper into what a macro rule is here; later chapters will introduce it specifically, and it won't affect the upcoming study.
There are two main ways to output text in Rust: println!() and print!(). Both "functions" output strings to the command line, differing only in that the former appends a newline at the end of the output. When using these two "functions" to output information, the first argument is a format string, followed by a series of variable arguments corresponding to the "placeholders" in the format string—this is very similar to the printf function in C. However, the placeholders in Rust's format strings are not "% + letter" in the form, but a pair of {}。
Example: runoob.rs file
fn
main
(
)
{
let
a
=
12
;
println
!
(
"a is {}"
,
a
)
;
}
Compile the runoob.rs file using the rustc command:
$ rustc runoob.rs # 编译 runoob.rs 文件
After compilation, an runoob executable file is generated:
$ ./runoob # 执行 runoob
The output of the program above 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's a better way:
println!("a is {0}, a again is {0}", a);
You can put a number between the {} which will treat the following variable arguments as an array, with indices starting from 0.
If you want to output { or } , what should you do? In the format string, use {{ and }} to escape and represent { and } respectively. But other common escape characters are the same as those in C, all in the form starting with a backslash.
fn main() {
println!("{{}}");
}
The output of the program above is:
{}