- Rust Essentials(Second Edition)
- Ivo Balbaert
- 368字
- 2021-07-02 15:30:38
Printing with string interpolation
An obvious way to use variables is to print out their value, as is done here:
// see Chapter 2/code/constants2.rs static MAX_HEALTH: i32 = 100; static GAME_NAME: &str = "Monster Attack"; const MYPI: f32 = 3.14; fn main() { println!("The Game you are playing is called {}.", GAME_NAME); println!("You start with {} health points.", MAX_HEALTH); }
This gives an output which looks like this:
The Game you are playing is called Monster Attack.
You start with 100 health points.
The first argument of the println! macro is a literal format string containing a placeholder {}. The value of the constant or variable after the comma is converted to a string and comes in its place. There can be more than one placeholder and they can be numbered in order, so that they can be used repeatedly, as in the following code:
println!("In the Game {0} you start with {1} % health, yes you read it correctly: {1} points!", GAME_NAME, MAX_HEALTH);
This produces the following output:
In the Game Monster Attack you start with 100 % health, yes you read it correctly: 100 points!
The placeholder can also contain one or more named arguments, like this:
println!("You have {points} % health", points = 70);
This produces the following output:
You have 70 % health
Special ways of formatting can be indicated inside the {} after a colon (:), optionally prefixed by a position, like this:
println!("MAX_HEALTH is {:x} in hexadecimal", MAX_HEALTH); //
This gives an output like this: 64
println!("MAX_HEALTH is {:b} in binary", MAX_HEALTH); //
This gives an output like this: 1100100
println!( "Two written in binary is {0:b}", 2); //
This gives an output like this: 10
println!("pi is {:e} in floating point notation", PI); //
This gives an output like this: 3.14e0.
The following formatting possibilities exist:
- o: For octal
- x: For lower hexadecimal
- X: For upper hexadecimal
- p: For a pointer
- b: For binary
- e: For lower exponential notation
- E: For upper exponential notation
- ?: For debugging purposes
The format! macro has the same parameters and works the same way as the println! macro, but it returns a string instead of printing out.
- C++程序設(shè)計(jì)教程
- 程序員面試筆試寶典
- Vue.js 3.x從入門(mén)到精通(視頻教學(xué)版)
- MATLAB應(yīng)用與實(shí)驗(yàn)教程
- Mastering Swift 2
- MATLAB for Machine Learning
- Learning JavaScript Data Structures and Algorithms(Second Edition)
- Troubleshooting Citrix XenApp?
- 區(qū)塊鏈架構(gòu)之美:從比特幣、以太坊、超級(jí)賬本看區(qū)塊鏈架構(gòu)設(shè)計(jì)
- Python預(yù)測(cè)之美:數(shù)據(jù)分析與算法實(shí)戰(zhàn)(雙色)
- Java EE架構(gòu)設(shè)計(jì)與開(kāi)發(fā)實(shí)踐
- LabVIEW數(shù)據(jù)采集
- Java面試一戰(zhàn)到底(基礎(chǔ)卷)
- VC++ 2008專(zhuān)題應(yīng)用程序開(kāi)發(fā)實(shí)例精講
- Illustrator CS6中文版應(yīng)用教程(第二版)