import ( "go/token" "io/ioutil" ) func main() { fs := token.NewFileSet() // Read file contents from disk content, err := ioutil.ReadFile("test.go") if err != nil { panic(err) } // Add the file to the FileSet file := fs.AddFile("test.go", fs.Base(), len(content)) // Add a token position to the file pos := file.Pos(10) // create a token position at offset 10 }
import ( "go/token" "io/ioutil" ) func main() { fs := token.NewFileSet() // Read file contents from disk content, err := ioutil.ReadFile("test.go") if err != nil { panic(err) } // Add the file to the FileSet file := fs.AddFile("test.go", fs.Base(), len(content)) // Get the source code for a given file position position := token.Pos(10) line := file.Line(position) source := file.LineStart(line) // start of the line if source < len(content) { sourceEnd := file.LineEnd(line) // end of the line code := string(content[source:sourceEnd]) println(code) } }This example shows how to extract a source code line from a file by using the File type's Line, LineStart, and LineEnd functions. Package library: go/token is part of the standard Go library.