我收到错误:Info doesn't implement Display (required by {}):11运行此代码时:
struct Info<'a> {
name: &'a str,
age: u8,
}
fn main() {
let john = Info {
name: "John",
age: 32,
};
println!("{}", john);
}
Run Code Online (Sandbox Code Playgroud)
我不知道我做错了什么。谁能给我解释一下吗?
Iva*_*n C 22
为了使结构可以通过"{}"格式说明符进行格式化,它需要实现该std::fmt::Display特征。
因此,要使代码编译,您需要impl Display for Info:
impl std::fmt::Display for Info<'_> {
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
write!(fmt, "My name is {} and I'm {} years old.", self.name, self.age)
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,Displaytrait 通常用于面向用户的表示。
或者,您可以在类型上使用"{:?}"格式说明符和注释来使用特征提供的格式化程序:#[derive(Debug)]std::fmt::Debug
#[derive(Debug)]
struct Info<'a> {
name: &'a str,
age: u8,
}
fn main() {
let john = Info {
name: "John",
age: 32,
};
println!("{:?}", john);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12154 次 |
| 最近记录: |