Search code examples
rustrakurust-polars

Rust Polars - get a struct Series from df.column instead of an '&' reference


I am building an interface from Raku NativeCall to Rust Polars to get that cool Arrow2 performance boost. At the high level I would like to work with Polars structs such as DataFrame and Series as attributes of matching containers. So to do df.column I would like something like this...

use polars::prelude::*;//{CsvReader, DataType, Field, Schema, DataFrame,};
use polars::prelude::{Result as PolarResult};
use polars::frame::DataFrame;
use polars::datatypes::DataType;

pub struct DataFrameC {
    df: DataFrame,
}

impl DataFrameC {
    fn new() -> DataFrameC {
        DataFrameC {
            df: DataFrame::default(),
        }   
    }   

    fn column(&self, string: String) -> Series {
        //let colin = self.df.column(&string).unwrap().head(Some(23));
        let colin = self.df.column(&string).unwrap()
        println!{"{}", colin};
        colin
    }
}

(similar approach for Series - so next steps to complete this fn is to make a Series::new() and then se.set(colin))

BUT - I can't work out how to deref a Polars Series & reference to a plain Series (I have tried .Deref() and .from_ptr() but these methods do not exist).

I have worked out that Series.head() does return a Series struct --- so the // line works as intended (but not the whole Series!)

I keep getting this error:

error[E0308]: mismatched types
  --> src/lib.rs:92:9
   |
88 |     fn column(&self, string: String) -> Series {
   |                                         ------ expected `polars::prelude::Series` because of return type
...
92 |         colin
   |         ^^^^^ expected struct `polars::prelude::Series`, found `&polars::prelude::Series`

For more information about this error, try `rustc --explain E0308`.
error: could not compile `dan` due to previous error

Is there a idiom for doing this deref action?

Any advice much appreciated!


Solution

  • You cannot deref a &Series into Series, because Series is not Copy. The &Series you get from self.df.column(&string).unwrap() is owned by the DataFrame.

    To return a Series, you must clone it. Don't worry it is a super cheap clone, because a Series is nothing but an Arc<ChunkedArray>, so the clone only does a single atomic reference count operation.