source := "2 + 3" expr, err := parser.ParseExpr(source) if err != nil { log.Fatal(err) }
source := "fmt.Println(\"Hello, World!\")" expr, err := parser.ParseExpr(source) if err != nil { log.Fatal(err) } callExpr, ok := expr.(*ast.CallExpr) if !ok { log.Fatal("not a function call expression") } arg := callExpr.Args[0].(*ast.BasicLit) fmt.Printf("Argument value: %s\n", arg.Value)
id := &ast.Ident{ Name: "x" } value := &ast.BasicLit{ Kind: token.INT, Value: "42" } expr := &ast.BinaryExpr{ X: id, Op: token.ADD, Y: value }In these examples, we've used the go.ast.Expr type to parse and manipulate Go source code at the AST level. The package library is the built-in go.ast package.