获得徽章 0
- Rust 代码片段 Box<dyn Any>:
use std::any::Any;
fn print_if_string(s: Box<dyn Any>) {
if s.is::<String>() {
println!("It's a string...");
} else {
println!("Not a string...");
}
}
fn main() {
let new_string = "hello".to_string();
print_if_string(Box::new(new_string));
}展开评论点赞 - Rust 代码片段 -- dyn Any:
use std::any::Any;
fn print_if_string(s: &dyn Any) {
if s.is::<String>() {
println!("It's a string!");
} else {
println!("Not a string!");
}
}
fn main() {
print_if_string(&"hello".to_string());
}展开评论点赞 - Rust 代码片段 -- 之 dyn Any(with TypeId):
use std::any::{Any, TypeId};
fn main() {
fn is_string(s: &dyn Any) {
if TypeId::of::<String>() == s.type_id() {
println!("It's a string!");
} else {
println!("Not a string!");
}
}
is_string(&"hello".to_string());
}展开评论点赞 - Rust 为 newtype 实现 Display
struct Meters(u32);
impl fmt::Display for Meters {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0)
}
}展开评论点赞