Search code examples
rustrust-polars

How to pass variable from one method to another in impl (in Rust)


Specific Question

I need to pass csv variable from load_csv function to operations function.

Code

use polars::{
    prelude::{CsvReader, SerReader},
    frame::DataFrame,
    error::PolarsResult
};

struct Boilerplate {}

impl Boilerplate {
    fn load_csv(&self) -> PolarsResult<DataFrame> {
        
        let csv = CsvReader::from_path("microsoft stock data.csv")?
        .has_header(true)
        .finish();

        // println!("{:?}", csv);

        csv
    }

    fn operations() {

    }
}

fn main() {
    let boilercode = Boilerplate{};
    println!("{:?}", boilercode.load_csv());
}

What I've tried (But, Didn't Work)

  1. Declared csv variable inside main function, then tried to access it in impl.


Solution

  • You can do something like this, storing your csv in the instance of your Boilerplate.

    struct Boilerplate {
        csv: PolarsResult<DataFrame>
    }
    
    impl Boilerplate {
        fn new() -> Boilerplate {
            Boilerplate {
                csv: CsvReader::from_path("microsoft stock data.csv")?
                       .has_header(true)
                       .finish();
        }
    
        fn operations(&self) {
            // work with self.csv
        }
    }
    
    fn main() {
        let boilercode = Boilerplate::new()
        println!("{:?}", boilercode.csv);
    
        boilercode.operations()
    }
    
    

    It's a little different then your current implementation, but I find this to be cleaner. And it also gives you the freedom to call your impl methods from others while keeping csv data in the instance. Like this:

    impl Boilerplate {
        // --snip--
        fn process(&self) {
            self.operations()
        }
    
        fn operations(&self) {
            // work with self.csv
        }
    }