使用fmt :: Display进行打印

Del*_*ore 4 printing rust

我正在尝试使用fmt :: Display打印枚举(或结构).虽然代码编译并获取显示方法,但它不会打印该值.

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
    }
}
Run Code Online (Sandbox Code Playgroud)

我尝试使用{:?}和{}但无济于事.

eul*_*isk 5

发生这种情况是因为Rust测试程序隐藏了成功测试的标准.您可以通过以下方式禁用此行为:--nocapture选项以测试二进制或货物测试命令:

cargo test -- --nocapture
Run Code Online (Sandbox Code Playgroud)

PS:您的代码已损坏/不完整