Golang go/parser.ParseExpr() function example

package go/parser

ParseExpr is a convenience function for obtaining the AST of an expression x. The position information recorded in the AST is undefined. The filename used in error messages is the empty string.

Golang go/parser.ParseExpr() function usage example

 var TypeExprs = map[string]TypeExpr{
 "int": TypeExpr{"int", "", 0, true},
 "*int": TypeExpr{"*int", "", 1, true},
 "[]int": TypeExpr{"[]int", "", 2, true},
 "...int": TypeExpr{"[]int", "", 2, true},
 "[]*int": TypeExpr{"[]*int", "", 3, true},
 "...*int": TypeExpr{"[]*int", "", 3, true},
 "MyType": TypeExpr{"MyType", "pkg", 0, true},
 "*MyType": TypeExpr{"*MyType", "pkg", 1, true},
 "[]MyType": TypeExpr{"[]MyType", "pkg", 2, true},
 "...MyType":  TypeExpr{"[]MyType", "pkg", 2, true},
 "[]*MyType":  TypeExpr{"[]*MyType", "pkg", 3, true},
 "...*MyType": TypeExpr{"[]*MyType", "pkg", 3, true},
 }

 for typeStr, expected := range TypeExprs {
 // Handle arrays and ... myself, since ParseExpr() does not.
 array := strings.HasPrefix(typeStr, "[]")
 if array {
 typeStr = typeStr[2:]
 }
 ellipsis := strings.HasPrefix(typeStr, "...")
 if ellipsis {
 typeStr = typeStr[3:]
 }
 expr, err := parser.ParseExpr(typeStr) // <-- here
 if err != nil {
 t.Error("Failed to parse test expr:", typeStr)
 continue
 }

References :

https://github.com/revel/revel/blob/master/harness/reflect_test.go

http://golang.org/pkg/go/parser/#ParseExpr

Advertisement