fix: 优化字符串类型在不同场景的打印形式

This commit is contained in:
0264408
2026-06-17 16:08:40 +08:00
parent e356c208a6
commit df9ecb4de1
+15 -3
View File
@@ -71,18 +71,30 @@ impl std::fmt::Debug for Value {
} }
} }
impl Value {
/// 容器内值的格式化:字符串加引号以区分类型,其余类型用 Display
fn fmt_element(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Value::String(s) => write!(f, "\"{}\"", s),
other => write!(f, "{}", other),
}
}
}
impl fmt::Display for Value { impl fmt::Display for Value {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self { match self {
Value::Number(n) => write!(f, "{}", n), Value::Number(n) => write!(f, "{}", n),
Value::String(s) => write!(f, "\"{}\"", s), Value::String(s) => write!(f, "{}", s),
Value::Bool(b) => write!(f, "{}", b), Value::Bool(b) => write!(f, "{}", b),
Value::Nil => write!(f, "nil"), Value::Nil => write!(f, "nil"),
Value::Object(obj) => { Value::Object(obj) => {
let obj = obj.borrow(); let obj = obj.borrow();
write!(f, "{{ ")?; write!(f, "{{ ")?;
for (key, value) in obj.iter() { for (key, value) in obj.iter() {
write!(f, "{}: {}, ", key, value)?; write!(f, "{}: ", key)?;
value.fmt_element(f)?;
write!(f, ", ")?;
} }
write!(f, "}}") write!(f, "}}")
}, },
@@ -93,7 +105,7 @@ impl fmt::Display for Value {
if i > 0 { if i > 0 {
write!(f, ", ")?; write!(f, ", ")?;
} }
write!(f, "{}", val)?; val.fmt_element(f)?;
} }
write!(f, "]") write!(f, "]")
}, },