Fn fmt calls itself recursively. How to stop?

use std::fmt;
 
enum LiteralInfo {
    String(String),
    Integer(i32),
    Float(f32),
    Long(i64),
    Double(f64),
}

impl fmt::Display for LiteralInfo {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Literal {} ", self )
    }
}   
    
fn main() {
     println!("main");
     let i = LiteralInfo::Integer(42);
     println!("{}", i);
     let i = LiteralInfo::String("Hello".to_string());
     println!("{}", i);
} 

It looks such an innocent program but I was a bit surprised that I ended up with stack overflow errors.
The format specifier in fn mut is calling fn mut again. What is the best way to solve this? Thanks.

I'd unpack your enum inside fmt:

use std::fmt;
 
enum LiteralInfo {
    String(String),
    Integer(i32),
    Float(f32),
    Long(i64),
    Double(f64),
}

impl fmt::Display for LiteralInfo {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::String(s) => write!(f, "Literal {s} "),
            Self::Integer(i) => write!(f, "Literal {i}"),
            _ => write!(f, "unimplemented"),
        }
    }
}   
    
fn main() {
     println!("main");
     let i = LiteralInfo::Integer(42);
     println!("{}", i);
     let i = LiteralInfo::String("Hello".to_string());
     println!("{}", i);
     let i = LiteralInfo::Double(0.);
     println!("{}", i);
}

Playground.

1 Like

Of course! Thank you.

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.