parse.ParseExpr("var a = 9") returns error "expected operand, found 'var'"

828 views
Skip to first unread message

Jason E. Aten

unread,
Aug 11, 2016, 6:55:49 AM8/11/16
to golang-nuts
I'm trying to use parser.ParseExpr. I'm thinking "var a = 9" is a valid expression, but ParseExpr returns an error:

// simple.go:

package main


import (

    "fmt"

    "go/parser"

)


func main() {

    ast0, err := parser.ParseExpr("var a = 9")

    fmt.Printf("err = %v\n", err)

    fmt.Printf("ast0 = %#v\n", ast0)

}


$go run simple.go

err = 1:1: expected operand, found 'var'

ast0 = <nil>

$


Pedantically, perhaps this is a statement rather than an expression. That begs the question, is there anyway to parse single statements (using go/parse)?

Martin Schnabel

unread,
Aug 11, 2016, 2:29:07 PM8/11/16
to golan...@googlegroups.com
On Do, 2016-08-11 at 03:55 -0700, Jason E. Aten wrote:
> I'm trying to use parser.ParseExpr. I'm thinking "var a = 9" is a
> valid expression, but ParseExpr returns an error:
>
hi jason, 
a variable declaration is a statement and not an expression.

when in question on this matters take a look at the spec.it is very
well written and readable as far as language specs go.

https://golang.org/ref/spec
i hope this helps

Martin Schnabel

unread,
Aug 11, 2016, 2:32:40 PM8/11/16
to golan...@googlegroups.com

> Pedantically, perhaps this is a statement rather than an expression.
> That begs the question, is there anyway to parse single statements
> (using go/parse)?

sorry haven't read the whole email.
just write your own. use a simple package file skeleton and use
ParseFile.
Reply all
Reply to author
Forward
0 new messages