Retrieving the expression from the type "ast.Expr" of an AST tree

1,428 views
Skip to first unread message

Steffi Mariya

unread,
Dec 3, 2013, 6:27:15 PM12/3/13
to golan...@googlegroups.com
I am trying to parse through a simple go program , which contains the expression “i:=2+3.4” using its AST tree, now when I try to parse through the Right-Hand-Side of my expression, I get elements of type “ast.Expr” which turns out to be “2+3.4” in my case, when I try to print this element it returns an address value 
&{0x2106c2760 102 + 0x2106c2780}

Is there any means I can get the string or part of the expression “2+3.4” from my AST tree instead of this address value? 

minux

unread,
Dec 3, 2013, 11:10:59 PM12/3/13
to Steffi Mariya, golang-nuts
ast.Expr is an interface, and what you get is an ast.BinaryExpr (actually a pointer to one)

You can use type assert to get it out from ast.Expr:
expr.(*ast.BinaryExpr)
And then you can inspect its fields X and Y, which is also an ast.Expr,
you might need type switches on them to extract the info you want
(for your specific example, they will be of type *ast.BasicLit)

Read about type assertions here: http://golang.org/ref/spec#Type_assertions

Matt Sherman

unread,
Dec 3, 2013, 11:12:56 PM12/3/13
to golan...@googlegroups.com
I had a similar issue (not quite the same), the solution was to go back to the source and take a substring using the Node's Pos() and End(). I wish there were a way to get the string straight from the Expr but it does not appear to be possible.

Here's a Stack answer, and here's my code.

Andrew Wilkins

unread,
Dec 4, 2013, 12:19:57 AM12/4/13
to golan...@googlegroups.com
Numerous. http://golang.org/pkg/go/printer/ is one option.

Steffi Mariya

unread,
Dec 4, 2013, 3:21:54 AM12/4/13
to golan...@googlegroups.com
Thank you everyone !
Based on the ast.Expr, I got the Node's position using the Pos() and End() methods and read the text(for that particular offset positions) in bytes format from the file. This method suited my need the best :)

Reply all
Reply to author
Forward
0 new messages