Ranking of values inside a struct

Hi everyone,

I am new to Rust and looking to see how I can implement an algorithm in the Rust way.
The context is set in a school setting, where the system is keeping track of the student's score.

There are four subjects that a student can take.

enum Subject {
    English, Math, Science, Geography
}

And each student will have the score stored together.

struct EnglishScore { score: i32 }
struct MathScore { score: i32 }
struct ScienceScore { score: i32 }
struct GeographyScore { score: i32 }

struct StudentSubjectScore {
    english: EnglishScore,
    math: MathScore,
    science: ScienceScore,
    geography: GeographyScore
}

And each of the language score struct have a trait called ToSubject that you can get the subject's enum.

trait ToSubject { fn get_subject() -> Subject; }

I want to be able to come out with a struct that is as follows that rank the subject from first to fourth.

struct StudentRankedSubject {
    first: Subject,
    second: Subject,
    third: Subject,
    fourth: Subject
}

Me having come from a OOP, Python and Ruby background.
I was thinking of implementing it as a Vec<i32> of all the scores, sort them and retrieve it from a generated HashMap.
But I realized I need to work through a number of Optional and leading to a situation where there could be None but not supposed to.

Just shouting out to see if anyone have a better solution out there.

Thanks in advanced!
JS

Using derive you can add an ordering to your own types. Using this you can define:

#[derive(PartialOrd, Ord, PartialEq, Eq, Debug)]
enum Subject {
    English, Math, Science, Geography
}

#[derive(PartialOrd, Ord, PartialEq, Eq, Debug)]
struct SubjectWithScore {
    score: u32,
    subject: Subject,
}

And then you can simply sort an array of value SubjectWithScore. See this playground for an example. Afterwards you can simply index into the sorted array to get the subjects out.

fn main() {
    let mut v = [
        SubjectWithScore { score: 10, subject: Subject::English },
        SubjectWithScore { score: 15, subject: Subject::Math },
        SubjectWithScore { score: 7, subject: Subject::Science },
        SubjectWithScore { score: 14, subject: Subject::Geography },
    ];
    v.sort();
    println!("{:#?}", v);
}

Note that if things have the same score, they will be sorted in the order they are defined in the enum.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.