In rust 1.0.0-nightly, this code works fine:
fn main() { let x = 10f64; let y = 20f64; let z = x + y; println!("z = {}", z); }
But if I try to use newtype (according to rust ):
struct Metres(f64); fn main() { let x = Metres(10f64); let y = Metres(20f64); let z = x + y; println!("z = {}", z); }
I get this compiler error:
test.rs:6:13: 6:18 error: binary operation `+` cannot be applied to type `Metres` test.rs:6 let z = x + y; ^~~~~ error: aborting due to previous error
Since Metres is basically f64 , why can't the compiler use the same + operator and create a new Metres object for z ?
How can I use newtypes if I cannot do simple things like adding and the like? How are they βvery usefulβ (as the book calls them)?
(There is an old question about this, but rust changes a lot, so I'm reasking)
source share