Standard library / go/token

go/token.File.Offset()

Converts a compact position to a zero-based byte offset, clamping outside bounds. Expected stdout: '3 0\n'.

Formal Syntax & Structure

go syntaxgo
func (f *File) Offset(p Pos) int

Parameters & Attributes

NameTypeDescription
pPosCompact source position in the associated file set.

Return Value

int

Converts a compact position to a zero-based byte offset, clamping outside bounds.

Working Example

Example Snippetgo
package main
import (  "fmt"  "go/token")
func main() {  s := token.NewFileSet()  f := s.AddFile("demo.go", -1, 5)  f.SetLinesForContent([]byte("ab\ncd"))  fmt.Println(f.Offset(f.Pos(3)), f.Offset(token.NoPos))}
Go Reference