Is there a way to implement this C macro in Go?

289 views
Skip to first unread message

sq...@google.com

unread,
Jul 22, 2016, 8:28:19 AM7/22/16
to golang-nuts
I've used this macro or some variant thereof in C/C++ for years:

  #define dump(x) printf("%s %d: %s = %d\n", __func__, __LINE__, #x, (int)(x))

The "#x" is the really useful part that lets you print the original expression. For example, if int a = 4 and int b = 10:

  dump(a + b);  // Prints "a + b = 14"

Is there a way to do this in Go? 

Sam Whited

unread,
Jul 22, 2016, 9:57:18 AM7/22/16
to sq...@google.com, golang-nuts
On Thu, Jul 21, 2016 at 7:09 PM, sque via golang-nuts
<golan...@googlegroups.com> wrote:
> The "#x" is the really useful part that lets you print the original
> expression. For example, if int a = 4 and int b = 10

This is not exactly the same, but %#v is probably what you want:

https://godoc.org/fmt#hdr-Printing

—Sam


--
Sam Whited
pub 4096R/54083AE104EA7AD3

Matt Harden

unread,
Jul 22, 2016, 12:27:58 PM7/22/16
to Sam Whited, sq...@google.com, golang-nuts
No, there's no way to do that in Go. There is no preprocessor nor any other way to obtain the original expression. You'll have to duplicate the expression as part of your format string.

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Val

unread,
Jul 25, 2016, 5:54:08 PM7/25/16
to golang-nuts, sq...@google.com
This code "does the trick" (except in Playground) :

https://play.golang.org/p/kJAfNFZUev

$ go run macro.go
dump(a + b) = 14
dump(b * a) = 40

$ go build -o macro
$ ./macro
dump(a + b) = 14
dump(b * a) = 40

Read current stacktrace, extract source file path, read source file, extract textual (uncompiled) expression.

Disclaimer : I have no idea what I'm talking about
Reply all
Reply to author
Forward
0 new messages