Rust print

From wikinotes
Revision as of 03:27, 9 February 2023 by Will (talk | contribs) (→‎Printing)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

https://rust-lang.github.io/rfcs/2795-format-args-implicit-identifiers.html

print

Printing

println!("hello");  // print to stdout
eprintln!("error"); // pritn to stderr

String Interpolation

let a = "A";
let b = "B";
println!("{a}--{b}");  // string interpolation

println!("hello, {name}", name="will"); // keyword assignment

Formatting

println!("Hello, {}", "alex");
println!("{0}, {0}, see {1}?", "alex", "movie");
println!("{person}, see {thing}?", person="alex", thing="movie");

Type Formatting

// formatting
println!("{:>4}", 2)             // "   2"  right align
println!("{:0>4}", 2)            // "0002"  right align, padded w/ zeros
println!("{var:>4}", var="boo")  // " boo"  right align

// type formatting
println!("{:X}", 1234)           // "4D2"   hex
println!("{:o}", 1234)           // "2322"  octal

Debug/Pretty Formatting

https://rust-lang.github.io/rfcs/2226-fmt-debug-hex.html?highlight=format#

println!("{:#?}", myvar) // pretty-print
println!("{:?}", myvar)  // debug info, for 'Debug' trait objects

dbg!

The dbg! macro is a special print macro intended for debugging.
If an object implements the Debug trait, you can use it to show

  • file
  • lineno
  • expression
  • result

It also returns the result of the expression, so you can wrap assignments in dbg! to capture the output.

#[derive(Debug)]
struct Foo{a: u8, b: u8}

let foo = Foo{a: 1, b: 2};
dbg!(foo)                 // print debug info about object
let result = dbg!(1 + 1)  // print debug info about expression