Template Toolkit 中是否有打印变量类型的语句?这是为了调试目的。 我试图找到类似的东西:
type(my_var)
输出:
scalar
答案 0 :(得分:1)
使用 PERL directive。示例:
use downcast_rs::{Downcast, impl_downcast};
use std::sync::{Arc, Mutex};
use std::any::Any;
trait Base: Downcast {}
impl_downcast!(Base);
#[derive(Debug)]
struct Foo {
/// A `u8` that is owned by this Foo, like a `Box<u8>`
x: *mut u8
}
impl Foo {
pub fn new(inner: Box<u8>) -> Self {
Foo {
x: Box::into_raw(inner)
}
}
pub fn access(&self) -> u8 {
unsafe {
// This is sound, because we 'own' x so only we have access
*self.x
}
}
}
// `x` is 'owned' (like a Box) so we may move it between threads,
// without fearing that it to gets deallocated
unsafe impl Send for Foo {}
impl Base for Foo {}
fn main() {
let x = Box::new(42);
// Move x into Foo (no references)
let foo = Foo::new(x);
// Create a shareable Foo
// Notice that `base` is Send & Sync
let base: Arc<Mutex<dyn Base + Send>> = Arc::new(Mutex::new(foo));
// Move it to an other thread
std::thread::spawn(move || {
// Lock mutex
let guard = base.lock().unwrap();
// Coerce to a simple trait object, so we can call trait-methods on it
let my_base: &dyn Base = &*guard;
if let Some(foo) = my_base.downcast_ref::<Foo>() {
println!("{:?} = {}", foo, foo.access());
} else {
println!("Not a Foo");
}
}).join();
}