Rust output to the command line


Release date:2023-11-04 Update date:2023-11-07 Editor:admin View counts:343

Label:

Rust output to the command line

Before formally learning the Rust language, we need to learn how to output aparagraph of text to the command line, which is a necessary skill before learning almost every language, because output to the command line is almostthe only way for the program to express the results in the language learning phase.

In the previous Hello, World program probably told you how to output a string, but it is not comprehensive, you may wonder why there is another println in println! (“Hello World”)! Symbol, does the Rust function have to be followed by an exclamation point? This is obviously not the case. Println is not a function, but a macro rule. There is no need to dig deeper into what the macro rules are, which will be covered in later chapters and will not affect the rest of the study.

There are two main ways for Rust to output text: println!() and print!() . Both functions are methods of outputting strings to the command line, except that the former appends a newline character to the end of the output. When using these two “functions” to output information, thefirst parameter is the format string, followed by a string of variable parameters, corresponding to the “placeholder” in the format string, whichis similar to that in the C language. printf function is very similar. However, the placeholder in the format string in Rust is not "% + letter" in the form of a pair {} .

Example: runoob.rs file

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

Use rustc command compilation runoob.rs file:

$ rustc runoob.rs   # compile runoob.rs file

Will be generated after compilation runoob executable file:

$ ./runoob    # execute runoob

The output of the above program is:

a is 12

If I wanted to output a twice, wouldn’t it be written as:

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

In fact, there is a better way to write:

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

In {} you can put a number between, which will access the subsequent variable parameters as an array, with the subscript starting at 0.

If you want to export { or } what should I do? In the format string through the {{ and }} escape the representative respectively { and } . But other commonly used escape characters, like those in C, are in the form of a backslash.

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

The output of the above program is:

{}

Powered by TorCMS (https://github.com/bukun/TorCMS).