How to pass variable from one method to another in impl

Specific Question

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


use polars::{
    prelude::{CsvReader, SerReader},
struct Boilerplate {}
impl Boilerplate {
    fn load_csv(&self) -> PolarsResult<DataFrame> {
        let csv = CsvReader::from_path("microsoft stock data.csv")?

        // println!("{:?}", 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.

I'm new to Rust. Sorry, in case it's a dumb question.
Thanks :smiley: !

It sounds like you want to pass the csv variable to your operations() method. Maybe something like this will help:

struct Boilerplate {}

impl Boilerplate {
  fn load_csv(&self) -> PolarsResult<DataFrame> { ... }

  fn operations(&self, csv: &DataFrame) { ... }  // (1)

fn main() {
  let boilerplate = Boilerplate {};
  let csv = boilerplate.load_csv().expect("Loading the CSV failed");  // (2)
  boilerplate.operations(&csv);  // (3)

There are a couple key things to take away here:

  1. I've added a csv: &DataFrame argument to operations() so we'll have access to the csv inside the method. I've also made sure operations() takes &self so it is a method callable on some boilerplate object as boilerplate.operations(&csv)
  2. We use expect() to get the DataFrame out of the PolarsResult, making the program crash if loading failed for some reason (there are better ways to handle errors, but blowing up will be good enough for now)
  3. In boilerplates.operations(&csv), I'm passing a reference to the csv variable into the operations() method (this ties in with point 1). I chose a reference here because often just looking at a data frame and doing analysis doesn't require you to consume it.
1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.