I found the post same as this title when I search some problem.
the original post is here.
@ExpHP gives a method using macro in that post , I paste it as follows
/// Extends a (possibly unsized) value with a Debug string.
// (This type is unsized when T is unsized)
pub struct Debuggable<T: ?Sized> {
text: &'static str,
value: T,
}
/// Produce a Debuggable<T> from an expression for T
macro_rules! dbg {
($($body:tt)+) => {
Debuggable {
text: stringify!($($body)+),
value: $($body)+,
}
};
}
// Note: this type is unsized
pub type PolFn = Debuggable<Fn(Rc<Pol>) -> Rc<Pol>>;
impl<T: ?Sized> fmt::Debug for Debuggable<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
{ write!(f, "{}", self.text) }
}
// This makes Debuggable have most methods of the thing it wraps.
// It also lets you call it when T is a function.
impl<T: ?Sized> ::std::ops::Deref for Debuggable<T>
{
type Target = T;
fn deref(&self) -> &T { &self.value }
}
fn main() {
let d: &PolFn = &dbg!(|x| {
let _ = "random code so you can see how it's formatted";
assert_eq!(3 * (1 + 2), 9);
x
});
println!("{:?}", d);
}
In the playground this prints:
| x | {
let _ = "random code so you can see how it's formatted" ; assert_eq ! (
3 * ( 1 + 2 ) , 9 ) ; x }
But this method will not print the actual value of a variable come from outside of closure, such as
fn main() {
let v = 10;
let d: &PolFn = &dbg!(|x: usize| {
let _ = "random code so you can see how it's formatted";
assert_eq!(3 * (1 + 2), 9);
if x > v {x} else {x * 2}
});
println!("{:?}", d);
}
the print result as folllows
| x: usize | {
let _ = "random code so you can see how it's formatted" ; assert_eq ! (
3 * ( 1 + 2 ) , 9 ) ; if x > v {x} else {x * 2} }
the variables 'v' is not be replaced with its actual value, how to make this method become more better that can print the actual value of the variable refered from outside of closure.
please help, thanks.