Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!
:timing
:sccache 1Tips and Traps¶
printlnis a macro (NOT a function) in Rust. A macro rule is invoke in the formatmacro_rule!to distinguish it from a regular function in Rust, soprintlnis invoked asprintln!.
Format an integer to its binary representation.
format!("{:b}", 15)"1111"format!("{:#b}", 15)"0b1111"println!("{:?}", (3, 4));(3, 4)
println!("{:#?}", (3, 4));(
3,
4,
)
format!("Hello"); // => "Hello"
format!("Hello, {}!", "world"); // => "Hello, world!"
format!("The number is {}", 1); // => "The number is 1"
format!("{:?}", (3, 4)); // => "(3, 4)"
format!("{value}", value=4); // => "4"
format!("{} {}", 1, 2); // => "1 2"
format!("{:04}", 42); // => "0042" with leading zerosPositional Parameters¶
format!("{1} {} {0} {}", 1, 2)"2 1 1 2"Named Parameters¶
format!("{argument}", argument = "test"); // => "test"
format!("{name} {}", 1, name = 2); // => "2 1"
format!("{a} {c} {b}", a="a", b='b', c=3); // => "a 3 b"Fill and Alignment¶
assert_eq!(format!("Hello {:<5}!", "x"), "Hello x !");
assert_eq!(format!("Hello {:-<5}!", "x"), "Hello x----!");
assert_eq!(format!("Hello {:^5}!", "x"), "Hello x !");
assert_eq!(format!("Hello {:>5}!", "x"), "Hello x!");Formatting Parameters¶
// All of these print "Hello x !"
println!("Hello {:5}!", "x");
println!("Hello {:1$}!", "x", 5);
println!("Hello {1:0$}!", 5, "x");
println!("Hello {:width$}!", "x", width = 5);println!("{}", 1)1
()println!("{:?}", 1)1
()