Advertisement
cwchen

[Rust] String formatting

Aug 26th, 2017
752
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 0.79 KB | None | 0 0
  1. fn main() {
  2.     // Hexadeicmal number
  3.     assert_eq!(format!("0x{:X}", 255), "0xFF");
  4.  
  5.     // Octal number
  6.     assert_eq!(format!("0o{:o}", 127), "0o177");
  7.  
  8.     // Decimal with specific precision
  9.     assert_eq!(format!("{:.2}", 3.14159), "3.14");
  10.  
  11.     // Formatted string for debug purpose
  12.     assert_eq!(format!("{:?}", vec![1, 2, 3]), "[1, 2, 3]");
  13.  
  14.     // Formatted string with specific position
  15.     assert_eq!(format!("{0}, this is {1}. {1}, this is {0}", "Alice", "Bob"),
  16.                "Alice, this is Bob. Bob, this is Alice");
  17.  
  18.     // Formatted string with specific name
  19.     assert_eq!(format!("{subject} {verb} {object}", object = "the lazy dog",
  20.                        verb = "jumps over", subject = "The swift fox"),
  21.                "The swift fox jumps over the lazy dog");
  22. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement