Formatted Print
std::fmt has utilities for formatting and printing Strings. Some of which include:
format!: write formatted text toStringprint!: same asformat!but the text is printed to the console (io::stdout).println!: same asprint!but a newline is appended.eprint!: same asprint!but the text is printed to the standard error (io::stderr).eprintln!: same aseprint!but a newline is appended.write!: emit the format string to a specified stream.writeln!same aswrite!but a newline is appended
Positional paramaters
#![allow(unused)] fn main() { println!("{1} {} {0} {}", 1, 2); // => 2 1 1 2 let formatted : String = format!("{1} {} {0} {}", 1, 2); println!("{formatted}"); // => 2 1 1 2 }
Named paramaters
#![allow(unused)] fn main() { let seven = 7; println!("{one} {two} ... {seven}", one = 1, two = 2); }
Escaping
The literal characters { and } may be included in a string by preceding them with the same character.
#![allow(unused)] fn main() { println!("Hello, {{}} {}", "{World!}"); }
Using write! of std::io::Write and std::fmt::Write
use std::io::{self, Write as _}; use std::fmt::Write as _; fn main() -> io::Result<()> { write!(&mut io::stdout(), "Hello, {}!", "World")?; let mut vec = Vec::new(); write!(&mut vec, "Hello, {}!", "World")?; assert_eq!(vec, b"Hello, World!"); let mut s = String::new(); write!(&mut s, "Life is {}", "Bootiful"); // std::fmt::Write assert_eq!(s, "Life is Bootiful"); Ok(()) }
Using format_args!
- result is of type
fmt::Arguments - result can be passed around
- no heap allocation
use std::io::{self, Write}; use std::fmt::{self}; fn write_error_log(arg: fmt::Arguments) -> std::io::Result<()>{ writeln!(&mut io::stdout(), "{}", arg )?; Ok(()) } fn main() -> io::Result<()> { write_error_log(format_args!("Error number is {}.", 1))?; Ok(()) }