use std::fmt::{Display, Formatter, Result};
use serde_aux::prelude::*;
use serde::Deserialize;
#[derive(Clone, Debug, Eq, PartialEq, Deserialize)]
pub struct Organism {
species: String,
#[serde(deserialize_with = "deserialize_number_from_string")]
taxon_code: u32,
common_name: String,
}
impl Display for Organism {
fn fmt(&self, f: &mut Formatter) -> Result {
write!(
f,
"{} - {} ({})",
self.common_name, self.taxon_code, self.species
)
}
}
impl Organism {
pub fn new(species: &str, taxon_code: &str, common_name: &str) -> Self {
let taxon_code_parsed: u32 = taxon_code.parse().unwrap();
Organism {
species: species.to_string(),
taxon_code: taxon_code_parsed,
common_name: common_name.to_string(),
}
}
pub fn common_name(&self) -> &str {
self.common_name.as_ref()
}
pub fn taxon_code(&self) -> u32 {
self.taxon_code
}
pub fn species(&self) -> &str {
self.species.as_ref()
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_organism_initialization() {
let org = Organism::new("Homo Sapiens", "9606", "Human");
assert_eq!(org.species, "Homo Sapiens");
assert_eq!(org.taxon_code, 9606);
assert_eq!(org.common_name, "Human")
}
#[test]
fn test_print() {
let org = Organism::new("Homo Sapiens", "9606", "Human");
assert_eq!(format!("{org}"), "Human - 9606 (Homo Sapiens)")
}
#[test]
fn test_getters() {
let org = Organism::new("Homo Sapiens", "9606", "Human");
assert_eq!(org.species(), "Homo Sapiens");
assert_eq!(org.taxon_code(), 9606);
assert_eq!(org.common_name(), "Human")
}
}