Formatting Print Statements
String formatting in Rust offers a multitude of options to control how information is presented. Let's delve into some of these formatting techniques with examples:
1. Default Formatting:
let c = 10.0 / 3.0;
println!("The result is: {}", c); // Default formatting
2. Specifying Decimal Precision:
let c = 10.0 / 3.0;
println!("The result is: {:.3}", c); // Display with three decimal places
3. Specifying Total Character Spaces with Padding:
let c = 10.0 / 3.0;
println!("The result is: {:8.3}", c); // Pad to occupy eight characters
4. Padding with Leading Zeros:
let c = 10.0 / 3.0;
println!("The result is: {:08.3}", c); // Pad with leading zeros
5. Displaying Multiple Variables:
let a = 10;
let c = 10.0 / 3.0;
println!("c is: {:08.3}\\na is: {}", c, a); // Display multiple variables
6. Positional Parameters:
let a = 10;
let c = 10.0 / 3.0;
println!("{0} is: {1:08.3}\\n{0} is: {1}", "c", c); // Using positional parameters
These examples showcase various string formatting techniques in Rust, offering flexibility and control over how data is presented. For more advanced formatting options, refer to the Rust documentation page for the standard format module.
Comments
Post a Comment