James's Ramblings

Rust

Created: April 02, 2021

Source: Rust By Example

Functions

Define a function:

fn main() {
}

Comments

Comments:

// Single line
/* Multi-
   line
*/
/* Neater
 * multi-
 * line
 */

Printing strings

  • 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 format! but the text is printed to the standard error (io::stderr).
  • eprintln!: same as eprint! but a newline is appended.
println!("{} days", 31);
// 31 days

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

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

 println!("{} of {:b} people know binary, the other half doesn't", 1, 2);
 // 1 of 10 people know binary, the other half doesn't

 println!("{number:>width$}", number=1, width=6);
 //      1
 // right-align

 println!("{number:>0width$}", number=1, width=6);
 // 000001
  • Cannot easily output custom types using these macros.
  • fmt:Display is a trait and uses the {} marker, as used above.
  • There is also fmt:Debug, which uses {:?} and is for debugging.