Golang go/token.FileSet.Pos type and IsValid() function examples

package go/token

type Pos int

Pos is a compact encoding of a source position within a file set. It can be converted into a Position for a more convenient, but much larger, representation.

The Pos value for a given file is a number in the range [base, base+size], where base and size are specified when adding the file to the file set via AddFile.

To create the Pos value for a specific source offset, first add the respective file to the current file set (via FileSet.AddFile) and then call File.Pos(offset) for that file. Given a Pos value p for a specific file set fset, the corresponding Position value is obtained by calling fset.Position(p).

Pos values can be compared directly with the usual comparison operators: If two Pos values p and q are in the same file, comparing p and q is equivalent to comparing the respective source file offsets. If p and q are in different files, p < q is true if the file implied by p was added to the respective file set before the file implied by q.

const NoPos Pos = 0

The zero value for Pos is NoPos; there is no file and line information associated with it, and NoPos().IsValid() is false. NoPos is always smaller than any other Pos value. The corresponding Position value for NoPos is the zero value for Position.

Golang go/token.FileSet.Pos type and IsValid() function usage examples

Example 1:

 var pos, end token.Pos
 if pos.IsValid() {
 p := info.FSet.Position(pos)
 relpath = p.Filename
 line = p.Line
 low = p.Offset
 }

 if end.IsValid() {
 high = info.FSet.Position(end).Offset
 }

Example 2:

 var comment string
 if pos := file.Pos(); pos.IsValid() {
 comment = "file " + check.fset.File(pos).Name()
 } 

References :

https://github.com/fzipp/pythia/blob/master/third_party/go.tools/go/types/check.go

http://golang.org/pkg/go/token/#FileSet.Pos

Advertisement