Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!
In [ ]:
:timing
:sccache 1
Tips and Traps¶
println
is 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, soprintln
is invoked asprintln!
.
Format an integer to its binary representation.
In [2]:
format!("{:b}", 15)
Out[2]:
In [2]:
format!("{:#b}", 15)
Out[2]:
In [10]:
println!("{:?}", (3, 4));
In [9]:
println!("{:#?}", (3, 4));
In [ ]:
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 zeros
Positional Parameters¶
In [9]:
format!("{1} {} {0} {}", 1, 2)
Out[9]:
Named Parameters¶
In [ ]:
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¶
In [ ]:
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¶
In [ ]:
// 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);
In [4]:
println!("{}", 1)
Out[4]:
In [5]:
println!("{:?}", 1)
Out[5]:
References¶
In [ ]: