【发布时间】:2023-01-10 12:50:30
【问题描述】:
像下面的代码, 当值是原始值或结构(具有派生调试属性)或其他内容时,它确实可以使用格式化打印来打印值。 但是当值是结构字段时我无法打印值。
#[derive(Debug)]
struct Point<T> {
x: T,
y: T,
}
fn main() {
let a = 3;
let p = Point { x: 5, y: 10 };
println!("{}", a); // Working
println!("{a}"); // Working
println!("{:?}", p); // Working
println!("{p:?}"); // Working
println!("{} {}", p.x, p.y); // Working
println!("{p.x} {p.y}"); // Not working
}
错误信息如下。
error: invalid format string: expected `'}'`, found `'.'`
--> src/main.rs:18:17
|
18 | println!("{p.x} {p.y}"); // Not working
| - ^ expected `}` in format string
| |
| because of this opening brace
|
= note: if you intended to print `{`, you can escape it using `{{`
error: could not compile `rust-ex` due to previous error
我认为 p.x 和 p.y 的类型是 i32 所以它们可以用格式化打印打印,但事实并非如此。 有没有办法用格式化程序打印打印结构字段?或者有什么需要执行的吗?
【问题讨论】:
标签: rust