rustreferencemutablerust-polarsborrow

Rust How to modify a polars DataFrame in a function, so that the caller see the changes?


I am lost at the mutable references ... Trying to send a DataFrame into a function ... change it and see the changes after the function call completes ...

I get error:

cannot borrow as mutable

Here is a code sample:

use polars::prelude::*;
use std::ops::DerefMut;

fn main() {
    let mut days = df!(
        "date_string" => &["1900-01-01", "1900-01-02", "1900-01-03", "1900-01-04", "1900-01-05",
        "1900-01-06", "1900-01-07", "1900-01-09", "1900-01-10"])
    .unwrap();

    change(&mut days);

    println!("{:?}", days);
    
}

fn change(days: &mut DataFrame) {
    days.column("date_string").unwrap().rename("DATE-STRING)");
}


Solution

  • The signature of column is

    fn column(&self, name: &str) -> Result<&Series, PolarsError>
    

    It returns a shared reference to a column. DataFrame has its own rename method that you should use:

    use polars::df;
    use polars::prelude::*;
    
    fn main() {
        let mut days = df!(
            "date_string" => &["1900-01-01", "1900-01-02", "1900-01-03", "1900-01-04", "1900-01-05",
            "1900-01-06", "1900-01-07", "1900-01-09", "1900-01-10"])
        .unwrap();
    
        change(&mut days).unwrap();
    
        assert_eq!(days.get_column_names(), &["DATE-STRING"]);
    }
    
    fn change(days: &mut DataFrame) -> Result<&mut DataFrame> {
        days.rename("date_string", "DATE-STRING")
    }