Printing using fmt :: Display

I am trying to print an enumeration (or structure) using fmt :: Display. Although the code compiles and switches to the display method, it does not 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.

+4
source share
3 answers

This is because the Rust testing program hides successful tests. You can disable this behavior by passing the -nocapture option to test a binary command or load test command as follows:

cargo test -- --nocapture

PS: your code is broken / incomplete

+5
source

-, , ; assert!, assert_eq! , .

, - . main:

use std::fmt;

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 {
        match self {
            &TestEnum::Foo(x) => write!(f, "{}", x),
            &TestEnum::Bar(x) => write!(f, "{}", x),
        }
    }
}

fn main() {
    let cell = TestEnum::Foo("foo");
    println!("Printing");
    println!("{}", cell);
}
+1

, , "FAILED" "ok".


- , panic!() , , . , @AndreaP , cargo test -- --nocapture .


stdout, , , :

let cell = TestEnum::Foo("foo");
let mut buf = Vec::new();
let _ = write!(buf, "{}\n", cell);
assert_eq!(&buf, b"foo\n");

- , stdout.

let _ = write!(io::stdout(), "{}\n", cell);

:

test tests::blub ... foo
ok

PlayPen

+1
source

All Articles