我跟着Rust by Example Docs, 我得到了一个编译器警告,我不明白。
考虑以下代码:
use std::fmt::{self, Display};
struct Matrix(f32, f32, f32, f32);
impl Display for Matrix {
fn fmt(&self, f : &mut fmt::Formatter) -> fmt::Result {
try!(writeln!(f, " ( {:.2}, {:.2} ) ", self.0, self.1));
write!(f, " ( {:.2}, {:.2} ) ", self.2, self.3)
}
}
fn main() {
let m = Matrix(1f32,2f32,3f32,4f32);
print!("{}", m);
}
此编译没有错误并且工作正常,但是如果我们从第一个try!
中移除writeln!
,那么该行就会变为
writeln!(f, " ( {:.2}, {:.2} ) ", self.0, self.1);
我收到此编译器警告:
<std macros>:2:1: 2:54 warning: unused result which must be used, #[warn(unused_must_use)] on by default
<std macros>:2 $ dst . write_fmt ( format_args ! ( $ ( $ arg ) * ) ) )
为什么?编译器试图告诉我什么? writeln!
是否会返回try!
正在检查的某种错误对象?
我在这里找到了writeln!
宏的来源:https://github.com/rust-lang/rust/blob/36d746718086dfcc12f73562b1996daf2f8ba643/src/libcore/macros.rs#L396
但我还不太了解它还没有回答我自己的问题。
rustc --version给了我rustc 1.10.0 (cfcb716cf 2016-07-03)
,如果那是相关的。
答案 0 :(得分:3)
write!
和writeln!
在传递给宏的第一个参数上调用名为write_fmt
的方法。这通常对应于std::io::Write
或std::fmt::Write
特征(首先要求您use
特征)或std::fmt::Formatter
结构中的方法。
您会注意到他们都返回Result
。 Result
具有#[must_use]
属性,该属性触发必须使用的&#34;未使用的结果&#34;警告。
print!
和println!
只返回()
。