Easiest way to have a set of functions do different things depending on a chosen option

Hi all,

I have a code that does exactly what I want on a structure:

pub struct ex {
    pub num: Vec<f64>,
}

impl ex {
    pub fn new() -> ex {
        let mut d = ex {
            num: Vec::with_capacity(168 * 168 * 20)
         };
     }
}

This is fine if I only ever have ex as a struct. But I want to have the new funtion also be available to something else, and to do something slightly different. But this other use case can't be used in conjunction with ex, they muct be mutually exclusive.

I was playing around with enums but I wasn't having much luck. If I've not done a good job at explaining, I don't mind elaborating, please let me know!

Many thanks,
Kev

I'm a little unclear on what you mean by making the new function "available". You mean you want it to possibly return different types of data depending on an option? You could do that with an enum:

pub struct ex {
    pub num: Vec<f64>,
}

pub enum Foo {
    Ex(ex),
    SomeOtherType(u32),
}

impl Foo {
    pub fn new(condition: bool) -> Foo {
        if condition {
            Foo::Ex(ex {
                num: Vec::with_capacity(168 * 168 * 20)
            })
        } else {
            Foo::SomeOtherType(123)
        }
    }
}

Can you give an example of an option you'd choose and what you'd want to happen based on that?

Hi @asymmetrikon,

Thanks or your reply. This is pretty much on the lines of what I need. I want to create 2 separate scoring functions. But it want the same functions to be usable with both types, but of course load in different files etc. based on which scoring function is wanted.

I hope this was a little clearer!

Edit: thanks for this, this works for a function. But it doesn’t work when I’m trying to do the same for a function that takes &mut self. Do you have a suggestion as to what the problem may be?

Many thanks,
Kev

Hi all,

I may have a simpler question actually. If I wanted to have two separate scoring functions scorefuncA and scorefuncB that can only be called exclusively. Both have the exact same functions that could be called on them, but how can I change the output of a function based on the scoring function that’s being called?

Many thanks,
Kev

It sounds like you want a trait:

trait ScoringMethod {
    fn calc(&self, in:usize)->usize;
}

struct ZeroScore;
impl ScoringMethod for ZeroScore {
    fn calc(&self, _:usize) { 0 }
}

struct DoubleScore;
impl ScoringMethod for DoubleScore {
    fn calc(&self, x:usize) { 2*x }
}

fn do_something(score: impl ScoringMethod)->usize {
    score.calc(42)
}

fn main() {
    println!("{}", do_something(ZeroScore)); // 0
    println!("{}", do_something(DoubleScore)); // 84
}
2 Likes

Thank you for all your help guys! I think I’ll try @2e71828 answer. I’ll let you know how I get on!

Many thanks,
Kev