Ben Chuanlong Du's Blog

It is never too late to learn.

The println Macro in Rust

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

  1. println is a macro (NOT a function) in Rust. A macro rule is invoke in the format macro_rule! to distinguish it from a regular function in Rust, so println is invoked as println!.

Format an integer to its binary representation.

In [2]:
format!("{:b}", 15)
Out[2]:
"1111"
In [2]:
format!("{:#b}", 15)
Out[2]:
"0b1111"
In [10]:
println!("{:?}", (3, 4));
(3, 4)
In [9]:
println!("{:#?}", (3, 4));
(
    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]:
"2 1 1 2"

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)
1
Out[4]:
()
In [5]:
println!("{:?}", 1)
1
Out[5]:
()

References

Module std::fmt

In [ ]:

Comments