package main import ( "fmt" "go/token" "go/parser" ) func main() { src := `package main import "fmt" func main() { fmt.Println("Hello, world!") }` fset := token.NewFileSet() ast, _ := parser.ParseFile(fset, "", src, 0) for _, node := range ast.Decls { for _, tok := range node.(*ast.GenDecl).TokPos { fmt.Printf("%v\t %v\n", fset.Position(tok), tok) } } }
package main import ( "fmt" "go/token" ) func main() { src := `package main import "fmt" func main() { fmt.Println("Hello, world!") }` fset := token.NewFileSet() file := fset.AddFile("", fset.Base(), len(src)) file.SetLinesForContent([]byte(src)) for _, line := range file.Lines { fmt.Printf("Line %d: %v\n", line.Number, line.Text) } }In this example, we use the `AddFile` and `SetLinesForContent` methods to create a new `token.File` that represents our Go program's source code. We then iterate over each line in the file using its `Lines` field to produce a set of numbered lines.