conversion.rs (1467B)
1 // Converting between custom types uses the From trait. 2 use std::fmt; 3 4 struct Complex { 5 real: f32, 6 imag: f32, 7 } 8 9 impl fmt::Display for Complex { 10 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 11 if self.imag == 0f32 { 12 write!(f, "{}", self.real)?; 13 } else { 14 write!(f, "{} + {}i", self.real, self.imag)?; 15 }; 16 Ok(()) 17 } 18 } 19 20 impl From<f32> for Complex { 21 fn from(item: f32) -> Self { 22 Complex { 23 real: item, 24 imag: 0f32, 25 } 26 } 27 } 28 29 fn main() { 30 // Create Complex from f32 31 let c = Complex::from(3.52); 32 println!("{}", c); 33 // Convert f32 `into` Complex 34 let ci: Complex = 8.49.into(); 35 println!("{}", ci); 36 37 // try_from and try_into are alternatives that allow errors, 38 // i.e. they return Result<Self, some_error_type>. 39 // (Will probably learn more about Result in error handling chapter) 40 41 // Converting a type into a String is a special case - the `ToString` trait. 42 // Usually you implement the fmt::Display to automatically get the ToString trait 43 // and allow printing with the `print!` macros as shown in `hellow_world.rs`. 44 45 // Parsing a string 46 let string = "8"; 47 let int: i32 = string.parse().unwrap(); 48 //let parsed: 49 println!( 50 "size of string '{}': {}", 51 string, 52 std::mem::size_of_val(string) 53 ); 54 println!("size of parsed int: {}", std::mem::size_of_val(&int)); 55 }