3rd
This commit is contained in:
52
src/main.rs
52
src/main.rs
@@ -1,3 +1,49 @@
|
||||
use std::fmt;
|
||||
|
||||
// use the automated debug as below
|
||||
//#[derive(fmt::Debug)]
|
||||
struct Vector2D {
|
||||
x: isize,
|
||||
y: isize,
|
||||
}
|
||||
|
||||
// Or write your own
|
||||
impl fmt::Debug for Vector2D {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
// The `f` value implements the `Write` trait, which is what the
|
||||
// write! macro is expecting. Note that this formatting ignores the
|
||||
// various flags provided to format strings.
|
||||
write!(f, "My Vector2D debug({}, {})", self.x, self.y)
|
||||
}
|
||||
}
|
||||
|
||||
// display cannot be automatically generated
|
||||
impl fmt::Display for Vector2D {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
// The `f` value implements the `Write` trait, which is what the
|
||||
// write! macro is expecting. Note that this formatting ignores the
|
||||
// various flags provided to format strings.
|
||||
write!(f, "({}, {})", self.x, self.y)
|
||||
}
|
||||
}
|
||||
|
||||
// Different traits allow different forms of output of a type. The meaning
|
||||
// of this format is to print the magnitude of a vector.
|
||||
impl fmt::Binary for Vector2D {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
let magnitude: f64 = (self.x * self.x + self.y * self.y) as f64;
|
||||
let magnitude = magnitude.sqrt();
|
||||
|
||||
// Respect the formatting flags by using the helper method
|
||||
// `pad_integral` on the Formatter object. See the method
|
||||
// documentation for details, and the function `pad` can be used
|
||||
// to pad strings.
|
||||
let decimals = f.precision().unwrap_or(3);
|
||||
let string = format!("{:.*}", decimals, magnitude);
|
||||
f.pad_integral(true, "", &string)
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
// In general, the `{}` will be automatically replaced with any
|
||||
// arguments. These will be stringified.
|
||||
@@ -46,4 +92,10 @@ fn main() {
|
||||
// handling. This will not work.
|
||||
//println!("This struct `{}` won't print...", Structure(3));
|
||||
// FIXME ^ Comment out this line.
|
||||
|
||||
let myvector = Vector2D { x: 3, y: 4 };
|
||||
|
||||
println!("{}", myvector); // => "(3, 4)"
|
||||
println!("{:?}", myvector); // => "Vector2D {x: 3, y:4}"
|
||||
println!("{:10.3b}", myvector); // => " 5.000"
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user