hello_world.rs (3387B)
1 fn main() { 2 /* 3 * Formatted print 4 */ 5 println!("My name is {0}, {1} {0}", "Bond", "James"); 6 let pi = 3.141592; 7 // Implicit position 8 println!("Pi is roughly {:.2}", pi); 9 // Explicit position 10 println!("Pi is roughly {0:.2}", pi); 11 // Named 12 println!("Pi is roughly {num:.2}", num = pi); 13 14 /* 15 * Debug 16 */ 17 println!("DEBUG"); 18 19 // v derive(DEBUG) trait lets you use {:?} in println!, but {} though 20 #[derive(Debug)] 21 struct Person<'a> { 22 name: &'a str, 23 age: u8, 24 } 25 let name = "Peter"; 26 let age = 27; 27 let peter = Person { name, age }; 28 29 // Pretty print 30 println!("{:?}", peter); 31 32 /* 33 * Display 34 */ 35 use std::fmt; 36 // Define a structure where the fields are nameable for comparison. 37 #[derive(Debug)] 38 struct Complex { 39 real: f64, 40 imag: f64, 41 } 42 43 // Implement `Display`, which defines how `{}` prints the struct in `println!` 44 // v derive(DEBUG) trait lets you use {:?} in println!, but {} though 45 impl fmt::Display for Complex { 46 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 47 // Customize so only `x` and `y` are denoted. 48 write!(f, "{} + {}i", self.real, self.imag) 49 } 50 } 51 52 println!("DISPLAY"); 53 println!( 54 "Display: {}", 55 Complex { 56 real: 3.3, 57 imag: 7.2 58 } 59 ); 60 61 println!( 62 "Debug: {:?}", 63 Complex { 64 real: 3.3, 65 imag: 7.2 66 } 67 ); 68 69 println!("TESTCASE: LIST"); 70 // Define a structure named `List` containing a `Vec`. 71 struct List(Vec<i32>); 72 73 impl fmt::Display for List { 74 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 75 // Extract the value using tuple indexing, 76 // and create a reference to `vec`. 77 let vec = &self.0; 78 79 write!(f, "[")?; 80 81 // Iterate over `v` in `vec` while enumerating the iteration 82 // count in `count`. 83 for (count, v) in vec.iter().enumerate() { 84 // For every element except the first, add a comma. 85 // Use the ? operator to return on errors. 86 if count != 0 { 87 write!(f, ", ")?; 88 } 89 write!(f, "{}: {}", count, v)?; 90 } 91 92 // Close the opened bracket and return a fmt::Result value. 93 write!(f, "]") 94 } 95 } 96 let v = List(vec![1, 2, 3]); 97 println!("{}", v); 98 99 println!("FORMATTING"); 100 101 #[derive(Debug)] 102 struct Color { 103 red: u8, 104 green: u8, 105 blue: u8, 106 } 107 108 impl fmt::Display for Color { 109 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 110 write!( 111 f, 112 "RGB ({0}, {1}, {2}) 0x{0:02X}{1:02X}{2:02X}", 113 self.red, self.green, self.blue 114 ) 115 } 116 } 117 for color in [ 118 Color { 119 red: 128, 120 green: 255, 121 blue: 90, 122 }, 123 Color { 124 red: 0, 125 green: 3, 126 blue: 254, 127 }, 128 Color { 129 red: 0, 130 green: 0, 131 blue: 0, 132 }, 133 ] 134 .iter() 135 { 136 // Switch this to use {} once you've added an implementation 137 // for fmt::Display. 138 println!("{}", *color); 139 } 140 }