Created
May 30, 2014 17:37
-
-
Save mitchmindtree/0b974e8b352b2d9a77e7 to your computer and use it in GitHub Desktop.
A question about rust generics.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
I want a 'MyStruct' that can take any of the floating point primitive types. | |
When instantiating a 'MyStruct', I want to do so with MyStruct::new(val), | |
which should create a struct with val: val, but should also initialise | |
a: 0.0(f32/f64 - whatever it's floating point type is) and | |
b: 1.0(f32/f64 - whatever it's floating point type is). | |
Can I do this with a single impl method (like below)? Am I on the right | |
track, or is there a better way to handle this situation in Rust? (I'm | |
coming from c++). | |
*/ | |
pub struct MyStruct<T> { | |
pub val: T, | |
a: T, | |
b: T | |
} | |
impl<T: Float> MyStruct<T> { | |
pub fn new(val: T) -> MyStruct<T> { | |
MyStruct{ | |
val: val, | |
a: 0.0, // Error: mismatched types: expected `T` but found `<generic float#0>` | |
b: 1.0 // Error: mismatched types: expected `T` but found `<generic float#1>` | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It turns out that one should use:
std::num::One::one() or std::num::Zero::zero() rather than primitives, as they are not automatically cast to the template's floating point type as in c / c++.