7.4. Rust output to the command line

发布时间 : 2025-10-25 13:33:17 UTC      

Page Views: 9 views

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 {} .

7.4.1. 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:

{} 
《地理信息系统原理、技术与方法》  97

最近几年来,地理信息系统无论是在理论上还是应用上都处在一个飞速发展的阶段。 GIS被应用于多个领域的建模和决策支持,如城市管理、区划、环境整治等等,地理信息成为信息时代重要的组成部分之一; “数字地球”概念的提出,更进一步推动了作为其技术支撑的GIS的发展。 与此同时,一些学者致力于相关的理论研究,如空间感知、空间数据误差、空间关系的形式化等等。 这恰好说明了地理信息系统作为应用技术和学科的两个方面,并且这两个方面构成了相互促进的发展过程。