package main import ( "go/ast" "go/token" ) func main() { expr := &ast.CallExpr{ Fun: &ast.Ident{Name: "print"}, Args: []ast.Expr{ &ast.BasicLit{Kind: token.STRING, Value: `"Hello, World!"`}, }, } pos := expr.Pos() // get the position of CallExpr println(pos.String()) // output: "1:1" }
package main import ( "go/ast" "go/parser" "go/token" "fmt" ) func main() { src := ` package main func main() { fmt.Println("Hello, World!") } ` fileSet := token.NewFileSet() file, err := parser.ParseFile(fileSet, "", src, parser.ParseComments) if err != nil { panic(err) } for _, stmt := range file.Decls { if funDecl, ok := stmt.(*ast.FuncDecl); ok && funDecl.Name.Name == "main" { for _, expr := range funDecl.Body.List { if callExpr, ok := expr.(*ast.CallExpr); ok && callExpr != nil { pos := callExpr.Pos() fmt.Println(pos.String()) // output: "5:13" } } } } }This example parses a Go source code string and extracts the position of the `fmt.Println` function call expression in the `main` function using the `CallExpr` and `Pos()` methods. The extracted source code position is then printed to the console. Library: go/ast, go/parser, go/token.