Looking for polymorphic(?) functions that would be known at compile time
I am still new to rust and this problem just cropped up in one of my projects.
The example from my project is that I have a struct and an impl for a SourceModel. This has a function called get_low(self, index). There are two implementations of get_low that do the same thing but would be used in different instances. When to use each instance would be known at compile time.
Here is a link to a playground explaining what I am trying to do with a dummy example.
text from playground:
/*
So what I am looking for is the ability to choose
which version of a function is run when it is called
but I cant figure it out.
I either want to specificy which version to use
when the function is called or I want to specificy
which version is used when the struct is actually created.
Below is an example of what I mean.
*/
pub struct SimpleMath {
pub x: i32,
pub y: i32,
}
impl SimpleMath {
pub fn mul(&self, val: i32) -> i64 {
val as i64 * self.x as i64 * self.y as i64
}
/*
and what I want here is another version of mul with the same signature
that can do something different in the body but still retusn an i64
What I have tried is making two new traits that both:
impl TRAIT for SimpleMath
So when I then make the simple math I could use the trait type. But that
runs into the problem of how do I pass that instance to another function that expects either
version of the trait.
If this makes very little sense I can make my project repo public and you can look at that instead.
*/
}
fn main() {
let math = SimpleMath { x: 3, y: 4 };
println!("{}", math.mul(4));
}
Thanks
Posted Mar 20, 2019, 6:12 PM UTC
311