你好,我是 Rust 的新手,只是在探索如何使用枚举。我有带有枚举的简单代码。
#[derive(Debug)]
enum Thing {
Str(String),
Boolean(bool)
}
fn run() -> Vec<Thing> {
let mut output: Vec<Thing> = Vec::new();
output.push(Thing::Str("Hello".to_string()));
output.push(Thing::Boolean(true));
return output
}
fn main() {
let result = run();
for i in result {
println!("{:?}", i)
}
}
当我运行这段代码时,它工作正常,但我得到这样的输出Str("Hello")
Boolean(true)
我怎样才能得到像"Hello"
true
所以我可以使用这个值进行进一步的处理,比如连接字符串或类似的东西。感谢帮助。
最佳答案
您正在使用 #[derive(Debug)]
宏,它会自动为您的类型定义 Debug 特征。打电话时println!("{:?}", i)
. {:?}
被称为“打印标记”,意思是“使用调试特性进行调试格式”。
你要使用的是Display
格式化,这需要 Display
的自定义实现特征。
一、实现Display
为 Thing
:
use std::fmt;
impl fmt::Display for Thing {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Thing::Str(s) => write!(f, "{}", s),
Thing::Boolean(b) => write!(f, "{}", b),
}
}
}
然后,您应该能够调用:println!("{}", i)
这将使用 Display trait 而不是 Debug trait。Debug和 Display如果您想了解有关格式化特征的更多信息,“Rust By Example”中的示例非常有用。
关于rust - [Rust 枚举] : How to get data value from mixed type enum in rust?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67714697/