I am building a rust program that takes values and lookups specifics of these values using a hash table. In order to make it more readable, I put the lookup table creation in its own file.
This is how the lookup table creation looks like:
(file: value_statistic_details.rs)
use std::collections::HashMap;
#[derive(Debug)]
pub struct ValueStatisticDetails {
pub unit: String,
pub unit_suffix: String,
pub stat_type: String,
}
#[allow(dead_code)]
pub fn value_create_hashmap() -> HashMap<String, ValueStatisticDetails> {
let mut value_statistic_details: HashMap<String, ValueStatisticDetails> = HashMap::new();
value_statistic_details.insert( String::from("all_operations_inflight"), ValueStatisticDetails { unit: String::from("operations"), unit_suffix: String::from("ops"), stat_type: String::from("gauge") } );
value_statistic_details.insert( String::from("alter_schema_operations_inflight"), ValueStatisticDetails { unit: String::from("operations"), unit_suffix: String::from("ops"), stat_type: String::from("gauge") } );
value_statistic_details.insert( String::from("block_cache_evictions"), ValueStatisticDetails { unit: String::from("blocks"), unit_suffix: String::from("blocks"), stat_type: String::from("counter") } );
value_statistic_details.insert( String::from("block_cache_hits"), ValueStatisticDetails { unit: String::from("blocks"), unit_suffix: String::from("blocks"), stat_type: String::from("counter") } );
return value_statistic_details;
}
In main.rs I incorporate it in the following way:
mod value_statistic_details;
use value_statistic_details::{ValueStatisticDetails, value_create_hashmap};
And then use it:
pub fn print_diff(value_diff: &BTreeMap<(String, String, String, String), SnapshotDiffValues>,
latency_diff: &BTreeMap<(String, String, String, String), SnapshotDiffLatencies>,
hostname_filter: &Regex,
stat_name_filter: &Regex,
table_name_filter: &Regex,
details_enable: &bool,
gauges_enable: &bool
) {
// value_diff
let value_statistic_details_lookup = value_create_hashmap();
for ((hostname, metric_type, metric_id, metric_name), value_diff_row) in value_diff {
if hostname_filter.is_match(&hostname) {
if stat_name_filter.is_match(&metric_name) {
if table_name_filter.is_match(&value_diff_row.table_name) {
let details = match value_statistic_details_lookup.get(&metric_name.to_string()) {
Some(x) => { ValueStatisticDetails { unit: x.unit.to_string(), unit_suffix: x.unit_suffix.to_string(), stat_type: x.stat_type.to_string() } },
None => { ValueStatisticDetails { unit: String::from("?"), unit_suffix: String::from("?"), stat_type: String::from("?") } }
};
...
If I don't include the dead_code hint, it will warn me that the function is never used, although I am using it?
I have the impression this can be done in a more rust-like way? Anyone willing to comment on my code?
These are snippets of my code, it doesn't work. This question is about doing it in a better and maybe more beautiful way. This is not about making it work: it works.