Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing using fmt::Display

Tags:

printing

rust

I am trying to print an enum (or structure) using fmt::Display. Though the code compiles and gets to the display method, it doesn't print the value.

pub enum TestEnum<'a> {
   Foo(&'a str),
   Bar(f32)
}

impl<'b> fmt::Display for TestEnum <'b> {
    fn fmt(&self, f : &mut fmt::Formatter) -> fmt::Result {
        println!("Got this far");
        match self{
            &TestEnum::Foo(x) => write!(f,"{}",x),
            &TestEnum::Bar(x) => write!(f,"{}",x),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn test_print() {
        let cell = TestEnum::Str("foo");
        println!("Printing");
        println!("{}",cell); // No output here
    }
}

I tried using {:?} and {} but to no avail.

like image 371
Delta_Fore Avatar asked Mar 16 '23 18:03

Delta_Fore


1 Answers

This happens because Rust test program hides stdout of successful tests. You can disable this behavior passing --nocapture option to test binary or to cargo test command this way:

cargo test -- --nocapture

PS: your code is broken/incomplete

like image 54
eulerdisk Avatar answered Mar 24 '23 14:03

eulerdisk