Standard library / go/types

go/types.Label.Pkg()

Returns the package associated with the object. The installed Pkg documentation says labels return nil, but a parsed label in Go 1.23.2 retains its enclosing package; do not assume nil. Expected stdout: 'true\n'.

Formal Syntax & Structure

go syntaxgo
func (obj *Label) Pkg() *Package

Return Value

*Package

Returns the package associated with the object.

Working Example

Example Snippetgo
package main
import (  "fmt"  "go/ast"  "go/constant"  "go/parser"  "go/token"  "go/types")
func check(e error) {  if e != nil {    panic(e)  }}func label() *types.Label {  _, i, _ := model()  for _, o := range i.Defs {    if l, ok := o.(*types.Label); ok {      return l    }  }  panic("missing label")}
func model() (*types.Package, *types.Info, *ast.File) {  f := token.NewFileSet()  file, e := parser.ParseFile(f, "demo.go", `package demo import alias "example.invalid/dep" const Answer = 42 var Count = alias.Number type CountAlias = int type Box[T any] struct{ Value T } func (b Box[T]) Get() T {return b.Value} func Work() {Start: for {break Start}} var Instance Box[int] `, 0)  check(e)  i := &types.Info{Defs: map[*ast.Ident]types.Object{}, Uses: map[*ast.Ident]types.Object{}, Implicits: map[ast.Node]types.Object{}, Types: map[ast.Expr]types.TypeAndValue{}, Scopes: map[ast.Node]*types.Scope{}, Instances: map[*ast.Ident]types.Instance{}}  p, e := (&types.Config{Importer: demoImporter{}}).Check("demo", f, []*ast.File{file}, i)  check(e)  return p, i, file}
type demoImporter struct{}
func (demoImporter) Import(path string) (*types.Package, error) {  p := types.NewPackage(path, "dep")  p.Scope().Insert(types.NewConst(0, p, "Number", types.Typ[types.Int], constant.MakeInt64(7)))  p.MarkComplete()  return p, nil}
func main() { v := label(); fmt.Println(v.Pkg() != nil && v.Pkg().Path() == "demo") }
Go Reference