2. format output

 

 


macro_rules

 

macros look like functions, except that their name ends with a bang !

// Macros are created using the macro_rules! macro.
macro_rules! say_hello {
    // `()` indicates that the macro takes no argument.
    () => {
        // The macro will expand into the contents of this block.
        println!("Hello!")
    };
}

 


Placeholders

 

{}

{x}

 


formatted text

 

// Only types that implement fmt::Display can be formatted with `{}`

    format!: write formatted text to String
    print!: same as format! but the text is printed to the console (io::stdout).
    println!: same as print! but a newline is appended.
    eprint!: same as print! but the text is printed to the standard error (io::stderr).
    eprintln!: same as eprint! but a newline is appended.

println! macro, which is provided by the std::fmt module in the standard library.

println!("{} days", 31);

println!("{0}, this is {1}. {1}, this is {0}", "Alice", "Bob");

println!("{subject} {verb} {object}",
    object="the lazy dog",
    subject="the quick brown fox",
    verb="jumps over");

{:b}
{:o}
{:x}
{:X}

println!("{number:>5}", number=1);
println!("{number:0>5}", number=1);
println!("{number:0<5}", number=1);

 


// which only applies to the module after it.
#[allow(dead_code)] // disable `dead_code` which warn against unused module

 


arguments in the "format specifier"

let number: f64 = 1.0;
let width: usize = 5;

// You can use named arguments in the "format specifier" by appending a `$`.
println!("{number:>width$}");

==============

https://doc.rust-lang.org/std/fmt/

format!("The number is {}", 1);


decimals to display

let pi = 3.141592;
println!("{:.2}", pi);

 


derive

// derive (automatically create) make this `struct` printable with `fmt::Debug`.
#[derive(Debug)]
struct Structure(i32);

// All std library types are automatically printable with {:?}
println!("Now {:?} will print!", Structure(3));

"pretty printing" with {:#?}

 


struct Person<'a> {
    name: &'a str,
    age: u8
}

 

Creative Commons license icon Creative Commons license icon