// Example 1: printing 'fmt.Println("Hello, World!")' func main() { ident := &ast.Ident{Name: "Println"} pkg := &ast.SelectorExpr{X: &ast.Ident{Name: "fmt"}, Sel: ident} args := []ast.Expr{&ast.BasicLit{Value: "\"Hello, World!\""}} callExpr := &ast.CallExpr{Fun: pkg, Args: args} ast.Print(token.NewFileSet(), callExpr) // Output: fmt.Println("Hello, World!") }
// Example 2: parsing 'foo(1, 2, 3)' func main() { expr, err := parser.ParseExpr("foo(1, 2, 3)") if err != nil { panic(err) } callExpression, ok := expr.(*ast.CallExpr) if !ok { fmt.Errorf("not a call expression") } // Is the function 'foo' being called? if ident, ok := callExpression.Fun.(*ast.Ident); ok { fmt.Printf("Called function %s\n", ident.Name) } // Output: Called function foo }This example uses go/parser package to parse the string "foo(1, 2, 3)" into an AST. CallExpr is then cast to *ast.CallExpr, and it is verified if it is calling a function 'foo'. It prints "Called function foo" if the called function is 'foo'. Overall, Go's CallExpr is a useful feature for working with abstract syntax trees. It is part of the go/ast package and can also be used with the go/parser package to parse and manipulate Go source code.