Skip to content

Instantly share code, notes, and snippets.

@mitchmindtree
Created May 30, 2014 17:37
Show Gist options
  • Save mitchmindtree/0b974e8b352b2d9a77e7 to your computer and use it in GitHub Desktop.
Save mitchmindtree/0b974e8b352b2d9a77e7 to your computer and use it in GitHub Desktop.
A question about rust generics.
/*
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>`
}
}
}
@mitchmindtree
Copy link
Author

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++.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment