3 ms·
Rust's dbg! is one of those ideas that felt obvious and beautiful once I saw it. Apparently it's inspired by Haskell.[0] I'd love to see it officially picked u
by JackC 6y ago
Rust's dbg! is one of those ideas that felt obvious and beautiful once I saw it.
Apparently it's inspired by Haskell.[0] I'd love to see it officially picked up in other languages.
[0] https://rust-lang.github.io/rfcs/2361-dbg-macro.html#prior-art https://rust-lang.github.io/rfcs/2361-dbg-macro.html#prior-a...
- lock-free 6y agoI've been using it in C/C++ projects going back at least 15 years, I thought it was commonplace for every language
- dagmx 6y agoDo you have an example of using it in C or C++?
- lock-free 6y agohttps://stackoverflow.com/questions/1644868/define-macro-for-debug-printing-in-c https://stackoverflow.com/questions/1644868/define-macro-for...
- steveklabnik 6y agoThere's a few significant differences here. This is a printf that only happens in debug mode; dbg is something that takes an expression, returns that expression, and will print out its filename, line number, and a pretty-printed version of the value. For an example of how this plays out, I had some code: let x = y + z; I wasn't sure what y was, so I was able to let x = dbg!(y) + z; this is much easier to insert into (and remove from) existing code. Plus, you don't need to write the formatting code. Basically, what you posted is in the same genre of thing, but is very different in a lot of meaningful ways.
- digikata 6y agoYou can use dbg inline within an expression!? How did I miss that?
- steveklabnik 6y agoYou can even use it inside itself. I've written let c = dbg!(dbg!(a) + dbg!(b)); one time...
- CJefferson 6y agoAfter I saw this in Rust, I had to implement it in C++: #include <iostream> #include <string> template<typename T> T print_dbg(T val, std::string exp, std::string file, int line) { std::cerr << exp << " = " << val << " @ " << file << ":" << line << "\n"; return val; } #define dbg(x) print_dbg(x,#x,__FILE__,__LINE__)
- petschge 6y agoClose. Applying that to double c = dbg(dbg(a) + dbg(b)); gives a = 1 @ debug.cxx:16 b = 2 @ debug.cxx:16 dbg(a) + dbg(b) = 3 @ debug.cxx:16 which has extra dbg()s on the third line. If I could I would probably want to write double dbg(c) = dbg(a) + dbg(b); but that of course doesn't work.
- dagmx 6y agoLike Steve said, what you're talking about is quite a bit different than what the rust dbg macro does.
- CyberDildonics 6y agoIt isn't really that different, it can just be used in inline expressions. Having the macro do nothing or just evaluating to the expression in debug mode is trivial, since a debug symbol would be defined.