打印值
你已经用过 println 和字符串插值来打印简单的值。
在字符串插值中,\{...} 里面的表达式会按照自己的输出格式转换成字符串,
然后插入到外层字符串中。当这个值有明确的显示格式时,这种写法很有用。
但是数据结构通常不同。有些数据结构没有面向显示的格式,因此不能直接用于
插值。当你想查看一个数组或其他结构化的值时,使用 to_repr:
println("emails: \{to_repr(emails)}")
to_repr 会产生一个 Repr:这个值的结构化、可读表示。它用于查看值,而
不是用于 JSON、XML、HTML 这样的自定义显示格式。例如,字符串数组会分成多行
打印,并且每个字符串都会带上双引号。
debug(x) 是 println("\{to_repr(x)}") 的简写。
Show 和 Debug
插值使用的输出格式由 Show trait 提供。当一个类型有明确的显示格式时,
可以提供 Show,例如普通文本、XML、JSON、HTML,或者其他格式。to_repr
和 debug 产生的结构化查看格式由 Debug trait 提供。trait 会在后面的
章节中介绍。
///|
fn main {
let name : String = "MoonBit"
let emails = [
"moonbit@example.email",
"moonbit-community@example.email",
"moonbit-x@example.email",
]
// 插值适合有显示格式的值。
println("name: \{name}")
// 想查看数据结构时,使用 to_repr。
println("emails: \{to_repr(emails)}")
// debug(x) 是 println("\{to_repr(x)}") 的简写。
debug(emails)
}