Skip to content

Match Function Call in Golang

Description

One of the common questions of ast-grep is to match function calls in Golang.

A plain pattern like fmt.Println($A) will not work. This is because Golang syntax also allows type conversions, e.g. int(3.14), that look like function calls.

To avoid this ambiguity, ast-grep lets us write a contextual pattern, which is a pattern inside a larger code snippet. We can use context to write a pattern like this: func t() { fmt.Println($A) }. Then, we can use the selector call_expression to match only function calls.

YAML

yaml
id: match-function-call
language: go
rule:
  pattern:
    context: 'func t() { fmt.Println($A) }'
    selector: call_expression

Example

go
func main() {
    fmt.Println("OK")
}

Contributed by

Inspired by QuantumGhost from ast-grep/ast-grep#646

Made with ❤️ with Rust