Curstom Formatting for Display

⚓ rust    📅 2025-05-27    👤 surdeus    👁️ 3      

surdeus

Warning

This post was published 33 days ago. The information described in this article may have changed.

So defined a struct for integer Polynomials, basically just holding the vector of coefficients like so:

use std::fmt;

fn main() {
    struct Polynomial {
        coefs: Vec<i32>,
    }

    impl fmt::Display for Polynomial {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            let mut result = format!("{}*T^0", self.coefs[0]);
            for (index, coef) in self.coefs[1..].iter().enumerate() {
                result = result + &format!(" + {}*T^{}", coef, index + 1);
            }
            return write!(f, "{}", result);
        }
    }

    let pol = Polynomial {
        coefs: vec![1, 0, 2],
    };
    println!("{}", pol)
}

This program prints 1*T^0 + 0*T^1 + 2*T^2 to the screen. However there would be about a gazillion other ways to print this polynomials:

1*T^0 + 0*T^1 + 2*T^2 (full)
1*T^0 + 2*T^2 (don't show 0 terms)
T^0 + 0*T^1 + 2*T^2 (don't show 1 coefficients)
T^0 + 2*T^2 (show neither)

I can think of many more options: order the terms from highest to lowest exponent, don't show T^0, print T^1 as T, etc.

My question is basically just if Formtters are suitable to implement this kind of formatting options, or if it is more appropriate to write a method like

    impl Polynomial {
        fn make_string(&self, show_0_terms: bool, show_1_coefs: bool, ascending: bool) -> String {}
    }

for this functionality?

3 posts - 3 participants

Read full topic

🏷️ rust_feed