georust / netcdf

High-level netCDF bindings for Rust
Apache License 2.0
81 stars 28 forks source link

How to read variables with string values? #103

Closed polvalente closed 1 year ago

polvalente commented 1 year ago

It seems that in 0.8.0 we need to pass a type template which implements a new trait that is only implemented for numbers. How can I load variables with strings as their values?

magnusuMET commented 1 year ago

This function is called string_value since we need to convert from nc_string to String

polvalente commented 1 year ago

Thank you! I managed to put the following code together. Leaving it as a reference for anyone that needs it :) I'm not that experienced in Rust, so suggestions are welcome, but I'm closing the issue!

fn load_string_variable_values(variable: &netcdf::variable::Variable) -> Result<Vec<String>, netcdf::error::Error> {
    let time_len = variable.len() as usize;
    let mut values: Vec<String> = Vec::with_capacity(time_len);

    for i in 0..time_len {
        let value: String = variable.string_value::<Extents>(i.into())?;
        values.push(value);
    }

    Ok(values)
}
magnusuMET commented 1 year ago

That snippet reads well. Another options is using iterator adaptors

fn load_string_variable_values(
    variable: &netcdf::variable::Variable,
) -> netcdf::error::Result<Vec<String>> {
    (0..variable.len() as usize)
        .map(|i| variable.string_value(i))
        .collect()
}