Coding

Understanding and Fixing the Rust Error: Result<DataFrame, PolarsError> cannot be formatted

Posted on Fri, Feb 14, 2025

Understanding and Fixing the Rust Error: Result<DataFrame, PolarsError> cannot be formatted

Recently I was working on a data analysis project and hit this basic error. I have had this many times and keep on forgetting about it, now I'm writing a post so that it will engrave the basics of Results and debug printing into my memory!

Rust is a powerful systems programming language known for its strict type safety and explicit error handling. However, these strengths can sometimes lead to frustrating compiler errors, especially for those new to Rust. One such error occurs when trying to print a Result<DataFrame, PolarsError> using println!.

The Error Explained

When attempting to print a DataFrame from the Polars library, you might run into an error message like this:

--> src/main.rs:15:20
   |
15 |     println!("{}", &df);
   |                    ^^^ `Result<DataFrame, PolarsError>` cannot be formatted with the default formatter
   |
   = help: the trait `std::fmt::Display` is not implemented for `Result<DataFrame, PolarsError>`, which is required by `&Result<DataFrame, PolarsError>: std::fmt::Display`
   = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead

The problem arises because df is not a DataFrame but a Result<DataFrame, PolarsError>. In Rust, Result is an enum used for error handling and does not implement std::fmt::Display, which is required for {} formatting in println!.

How to Fix It

There are multiple ways to resolve this issue, depending on how you want to handle the Result.

1. Use Debug Formatting

If you simply want to print df for debugging purposes, use {:?} instead of {}:

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

Or for pretty-printing with better readability:

println!("{:#?}", df);

2. Unwrap the Result (Only If Safe)

If you are sure df contains a valid DataFrame, you can use unwrap():

println!("{}", df.unwrap());

However, this will panic if df contains an error. Only use unwrap() if you're confident the result is always Ok.

3. Handle Errors Gracefully

A safer approach is to handle both the Ok and Err cases explicitly:

match df {
    Ok(ref dataframe) => println!("{}", dataframe),
    Err(ref e) => eprintln!("Error: {}", e),
}

Alternatively, using .unwrap_or_else(), you can provide a fallback action if df contains an error:

println!("{}", df.unwrap_or_else(|e| {
    eprintln!("Failed to load dataframe: {}", e);
    DataFrame::default() // Provide an empty DataFrame as a fallback
}));

Summary

Use {:?} or {:#?} to print debug output of the Result.

Use unwrap() cautiously, only if you're sure there will be no errors.

Handle errors properly using match or .unwrap_or_else().

By understanding Rust's error handling and formatting traits, you can debug issues more effectively and write more robust code. Happy coding!