Package types

import "go/types"
Overview
Index
Examples

Overview ▾

Package types declares the data types and implements the algorithms for type-checking of Go packages. Use Config.Check to invoke the type checker for a package. Alternatively, create a new type checker with NewChecker and invoke it incrementally by calling Checker.Files.

Type-checking consists of several interdependent phases:

Name resolution maps each identifier (ast.Ident) in the program to the symbol (Object) it denotes. Use the Defs and Uses fields of Info or the Info.ObjectOf method to find the symbol for an identifier, and use the Implicits field of Info to find the symbol for certain other kinds of syntax node.

Constant folding computes the exact constant value (constant.Value) of every expression (ast.Expr) that is a compile-time constant. Use the Types field of Info to find the results of constant folding for an expression.

Type deduction computes the type (Type) of every expression (ast.Expr) and checks for compliance with the language specification. Use the Types field of Info for the results of type deduction.

For a tutorial, see https://go.dev/s/types-tutorial.

Index ▾

Variables
func AssertableTo(V *Interface, T Type) bool
func AssignableTo(V, T Type) bool
func CheckExpr(fset *token.FileSet, pkg *Package, pos token.Pos, expr ast.Expr, info *Info) (err error)
func Comparable(T Type) bool
func ConvertibleTo(V, T Type) bool
func DefPredeclaredTestFuncs()
func ExprString(x ast.Expr) string
func Id(pkg *Package, name string) string
func Identical(x, y Type) bool
func IdenticalIgnoreTags(x, y Type) bool
func Implements(V Type, T *Interface) bool
func IsInterface(t Type) bool
func ObjectString(obj Object, qf Qualifier) string
func Satisfies(V Type, T *Interface) bool
func SelectionString(s *Selection, qf Qualifier) string
func TypeString(typ Type, qf Qualifier) string
func WriteExpr(buf *bytes.Buffer, x ast.Expr)
func WriteSignature(buf *bytes.Buffer, sig *Signature, qf Qualifier)
func WriteType(buf *bytes.Buffer, typ Type, qf Qualifier)
type Alias
    func NewAlias(obj *TypeName, rhs Type) *Alias
    func (a *Alias) Obj() *TypeName
    func (a *Alias) Origin() *Alias
    func (a *Alias) Rhs() Type
    func (a *Alias) SetTypeParams(tparams []*TypeParam)
    func (a *Alias) String() string
    func (a *Alias) TypeArgs() *TypeList
    func (a *Alias) TypeParams() *TypeParamList
    func (a *Alias) Underlying() Type
type ArgumentError
    func (e *ArgumentError) Error() string
    func (e *ArgumentError) Unwrap() error
type Array
    func NewArray(elem Type, len int64) *Array
    func (a *Array) Elem() Type
    func (a *Array) Len() int64
    func (a *Array) String() string
    func (a *Array) Underlying() Type
type Basic
    func (b *Basic) Info() BasicInfo
    func (b *Basic) Kind() BasicKind
    func (b *Basic) Name() string
    func (b *Basic) String() string
    func (b *Basic) Underlying() Type
type BasicInfo
type BasicKind
type Builtin
    func (obj *Builtin) Exported() bool
    func (obj *Builtin) Id() string
    func (obj *Builtin) Name() string
    func (obj *Builtin) Parent() *Scope
    func (obj *Builtin) Pkg() *Package
    func (obj *Builtin) Pos() token.Pos
    func (obj *Builtin) String() string
    func (obj *Builtin) Type() Type
type Chan
    func NewChan(dir ChanDir, elem Type) *Chan
    func (c *Chan) Dir() ChanDir
    func (c *Chan) Elem() Type
    func (c *Chan) String() string
    func (c *Chan) Underlying() Type
type ChanDir
type Checker
    func NewChecker(conf *Config, fset *token.FileSet, pkg *Package, info *Info) *Checker
    func (check *Checker) Files(files []*ast.File) (err error)
type Config
    func (conf *Config) Check(path string, fset *token.FileSet, files []*ast.File, info *Info) (*Package, error)
type Const
    func NewConst(pos token.Pos, pkg *Package, name string, typ Type, val constant.Value) *Const
    func (obj *Const) Exported() bool
    func (obj *Const) Id() string
    func (obj *Const) Name() string
    func (obj *Const) Parent() *Scope
    func (obj *Const) Pkg() *Package
    func (obj *Const) Pos() token.Pos
    func (obj *Const) String() string
    func (obj *Const) Type() Type
    func (obj *Const) Val() constant.Value
type Context
    func NewContext() *Context
type Error
    func (err Error) Error() string
type Func
    func MissingMethod(V Type, T *Interface, static bool) (method *Func, wrongType bool)
    func NewFunc(pos token.Pos, pkg *Package, name string, sig *Signature) *Func
    func (obj *Func) Exported() bool
    func (obj *Func) FullName() string
    func (obj *Func) Id() string
    func (obj *Func) Name() string
    func (obj *Func) Origin() *Func
    func (obj *Func) Parent() *Scope
    func (obj *Func) Pkg() *Package
    func (obj *Func) Pos() token.Pos
    func (obj *Func) Scope() *Scope
    func (obj *Func) Signature() *Signature
    func (obj *Func) String() string
    func (obj *Func) Type() Type
type ImportMode
type Importer
type ImporterFrom
type Info
    func (info *Info) ObjectOf(id *ast.Ident) Object
    func (info *Info) PkgNameOf(imp *ast.ImportSpec) *PkgName
    func (info *Info) TypeOf(e ast.Expr) Type
type Initializer
    func (init *Initializer) String() string
type Instance
type Interface
    func NewInterface(methods []*Func, embeddeds []*Named) *Interface
    func NewInterfaceType(methods []*Func, embeddeds []Type) *Interface
    func (t *Interface) Complete() *Interface
    func (t *Interface) Embedded(i int) *Named
    func (t *Interface) EmbeddedType(i int) Type
    func (t *Interface) Empty() bool
    func (t *Interface) ExplicitMethod(i int) *Func
    func (t *Interface) IsComparable() bool
    func (t *Interface) IsImplicit() bool
    func (t *Interface) IsMethodSet() bool
    func (t *Interface) MarkImplicit()
    func (t *Interface) Method(i int) *Func
    func (t *Interface) NumEmbeddeds() int
    func (t *Interface) NumExplicitMethods() int
    func (t *Interface) NumMethods() int
    func (t *Interface) String() string
    func (t *Interface) Underlying() Type
type Label
    func NewLabel(pos token.Pos, pkg *Package, name string) *Label
    func (obj *Label) Exported() bool
    func (obj *Label) Id() string
    func (obj *Label) Name() string
    func (obj *Label) Parent() *Scope
    func (obj *Label) Pkg() *Package
    func (obj *Label) Pos() token.Pos
    func (obj *Label) String() string
    func (obj *Label) Type() Type
type Map
    func NewMap(key, elem Type) *Map
    func (m *Map) Elem() Type
    func (m *Map) Key() Type
    func (t *Map) String() string
    func (t *Map) Underlying() Type
type MethodSet
    func NewMethodSet(T Type) *MethodSet
    func (s *MethodSet) At(i int) *Selection
    func (s *MethodSet) Len() int
    func (s *MethodSet) Lookup(pkg *Package, name string) *Selection
    func (s *MethodSet) String() string
type Named
    func NewNamed(obj *TypeName, underlying Type, methods []*Func) *Named
    func (t *Named) AddMethod(m *Func)
    func (t *Named) Method(i int) *Func
    func (t *Named) NumMethods() int
    func (t *Named) Obj() *TypeName
    func (t *Named) Origin() *Named
    func (t *Named) SetTypeParams(tparams []*TypeParam)
    func (t *Named) SetUnderlying(underlying Type)
    func (t *Named) String() string
    func (t *Named) TypeArgs() *TypeList
    func (t *Named) TypeParams() *TypeParamList
    func (t *Named) Underlying() Type
type Nil
    func (obj *Nil) Exported() bool
    func (obj *Nil) Id() string
    func (obj *Nil) Name() string
    func (obj *Nil) Parent() *Scope
    func (obj *Nil) Pkg() *Package
    func (obj *Nil) Pos() token.Pos
    func (obj *Nil) String() string
    func (obj *Nil) Type() Type
type Object
    func LookupFieldOrMethod(T Type, addressable bool, pkg *Package, name string) (obj Object, index []int, indirect bool)
type Package
    func NewPackage(path, name string) *Package
    func (pkg *Package) Complete() bool
    func (pkg *Package) GoVersion() string
    func (pkg *Package) Imports() []*Package
    func (pkg *Package) MarkComplete()
    func (pkg *Package) Name() string
    func (pkg *Package) Path() string
    func (pkg *Package) Scope() *Scope
    func (pkg *Package) SetImports(list []*Package)
    func (pkg *Package) SetName(name string)
    func (pkg *Package) String() string
type PkgName
    func NewPkgName(pos token.Pos, pkg *Package, name string, imported *Package) *PkgName
    func (obj *PkgName) Exported() bool
    func (obj *PkgName) Id() string
    func (obj *PkgName) Imported() *Package
    func (obj *PkgName) Name() string
    func (obj *PkgName) Parent() *Scope
    func (obj *PkgName) Pkg() *Package
    func (obj *PkgName) Pos() token.Pos
    func (obj *PkgName) String() string
    func (obj *PkgName) Type() Type
type Pointer
    func NewPointer(elem Type) *Pointer
    func (p *Pointer) Elem() Type
    func (p *Pointer) String() string
    func (p *Pointer) Underlying() Type
type Qualifier
    func RelativeTo(pkg *Package) Qualifier
type Scope
    func NewScope(parent *Scope, pos, end token.Pos, comment string) *Scope
    func (s *Scope) Child(i int) *Scope
    func (s *Scope) Contains(pos token.Pos) bool
    func (s *Scope) End() token.Pos
    func (s *Scope) Innermost(pos token.Pos) *Scope
    func (s *Scope) Insert(obj Object) Object
    func (s *Scope) Len() int
    func (s *Scope) Lookup(name string) Object
    func (s *Scope) LookupParent(name string, pos token.Pos) (*Scope, Object)
    func (s *Scope) Names() []string
    func (s *Scope) NumChildren() int
    func (s *Scope) Parent() *Scope
    func (s *Scope) Pos() token.Pos
    func (s *Scope) String() string
    func (s *Scope) WriteTo(w io.Writer, n int, recurse bool)
type Selection
    func (s *Selection) Index() []int
    func (s *Selection) Indirect() bool
    func (s *Selection) Kind() SelectionKind
    func (s *Selection) Obj() Object
    func (s *Selection) Recv() Type
    func (s *Selection) String() string
    func (s *Selection) Type() Type
type SelectionKind
type Signature
    func NewSignature(recv *Var, params, results *Tuple, variadic bool) *Signature
    func NewSignatureType(recv *Var, recvTypeParams, typeParams []*TypeParam, params, results *Tuple, variadic bool) *Signature
    func (s *Signature) Params() *Tuple
    func (s *Signature) Recv() *Var
    func (s *Signature) RecvTypeParams() *TypeParamList
    func (s *Signature) Results() *Tuple
    func (t *Signature) String() string
    func (s *Signature) TypeParams() *TypeParamList
    func (t *Signature) Underlying() Type
    func (s *Signature) Variadic() bool
type Sizes
    func SizesFor(compiler, arch string) Sizes
type Slice
    func NewSlice(elem Type) *Slice
    func (s *Slice) Elem() Type
    func (s *Slice) String() string
    func (s *Slice) Underlying() Type
type StdSizes
    func (s *StdSizes) Alignof(T Type) (result int64)
    func (s *StdSizes) Offsetsof(fields []*Var) []int64
    func (s *StdSizes) Sizeof(T Type) int64
type Struct
    func NewStruct(fields []*Var, tags []string) *Struct
    func (s *Struct) Field(i int) *Var
    func (s *Struct) NumFields() int
    func (t *Struct) String() string
    func (s *Struct) Tag(i int) string
    func (t *Struct) Underlying() Type
type Term
    func NewTerm(tilde bool, typ Type) *Term
    func (t *Term) String() string
    func (t *Term) Tilde() bool
    func (t *Term) Type() Type
type Tuple
    func NewTuple(x ...*Var) *Tuple
    func (t *Tuple) At(i int) *Var
    func (t *Tuple) Len() int
    func (t *Tuple) String() string
    func (t *Tuple) Underlying() Type
type Type
    func Default(t Type) Type
    func Instantiate(ctxt *Context, orig Type, targs []Type, validate bool) (Type, error)
    func Unalias(t Type) Type
type TypeAndValue
    func Eval(fset *token.FileSet, pkg *Package, pos token.Pos, expr string) (_ TypeAndValue, err error)
    func (tv TypeAndValue) Addressable() bool
    func (tv TypeAndValue) Assignable() bool
    func (tv TypeAndValue) HasOk() bool
    func (tv TypeAndValue) IsBuiltin() bool
    func (tv TypeAndValue) IsNil() bool
    func (tv TypeAndValue) IsType() bool
    func (tv TypeAndValue) IsValue() bool
    func (tv TypeAndValue) IsVoid() bool
type TypeList
    func (l *TypeList) At(i int) Type
    func (l *TypeList) Len() int
type TypeName
    func NewTypeName(pos token.Pos, pkg *Package, name string, typ Type) *TypeName
    func (obj *TypeName) Exported() bool
    func (obj *TypeName) Id() string
    func (obj *TypeName) IsAlias() bool
    func (obj *TypeName) Name() string
    func (obj *TypeName) Parent() *Scope
    func (obj *TypeName) Pkg() *Package
    func (obj *TypeName) Pos() token.Pos
    func (obj *TypeName) String() string
    func (obj *TypeName) Type() Type
type TypeParam
    func NewTypeParam(obj *TypeName, constraint Type) *TypeParam
    func (t *TypeParam) Constraint() Type
    func (t *TypeParam) Index() int
    func (t *TypeParam) Obj() *TypeName
    func (t *TypeParam) SetConstraint(bound Type)
    func (t *TypeParam) String() string
    func (t *TypeParam) Underlying() Type
type TypeParamList
    func (l *TypeParamList) At(i int) *TypeParam
    func (l *TypeParamList) Len() int
type Union
    func NewUnion(terms []*Term) *Union
    func (u *Union) Len() int
    func (u *Union) String() string
    func (u *Union) Term(i int) *Term
    func (u *Union) Underlying() Type
type Var
    func NewField(pos token.Pos, pkg *Package, name string, typ Type, embedded bool) *Var
    func NewParam(pos token.Pos, pkg *Package, name string, typ Type) *Var
    func NewVar(pos token.Pos, pkg *Package, name string, typ Type) *Var
    func (obj *Var) Anonymous() bool
    func (obj *Var) Embedded() bool
    func (obj *Var) Exported() bool
    func (obj *Var) Id() string
    func (obj *Var) IsField() bool
    func (obj *Var) Name() string
    func (obj *Var) Origin() *Var
    func (obj *Var) Parent() *Scope
    func (obj *Var) Pkg() *Package
    func (obj *Var) Pos() token.Pos
    func (obj *Var) String() string
    func (obj *Var) Type() Type

Examples

Info
MethodSet
Scope

Package files

alias.go api.go api_predicates.go array.go assignments.go badlinkname.go basic.go builtins.go call.go chan.go check.go const.go context.go conversions.go decl.go errors.go errsupport.go eval.go expr.go exprstring.go format.go gccgosizes.go gcsizes.go generate.go index.go infer.go initorder.go instantiate.go interface.go labels.go lookup.go map.go methodset.go mono.go named.go object.go objset.go operand.go package.go pointer.go predicates.go resolver.go return.go scope.go selection.go signature.go sizes.go slice.go stmt.go struct.go subst.go termlist.go tuple.go type.go typelists.go typeparam.go typeset.go typestring.go typeterm.go typexpr.go under.go unify.go union.go universe.go util.go validtype.go version.go

Variables

Typ contains the predeclared *Basic types indexed by their corresponding BasicKind.

The *Basic type for Typ[Byte] will have the name "uint8". Use Universe.Lookup("byte").Type() to obtain the specific alias basic type named "byte" (and analogous for "rune").

var Typ = []*Basic{
    Invalid: {Invalid, 0, "invalid type"},

    Bool:          {Bool, IsBoolean, "bool"},
    Int:           {Int, IsInteger, "int"},
    Int8:          {Int8, IsInteger, "int8"},
    Int16:         {Int16, IsInteger, "int16"},
    Int32:         {Int32, IsInteger, "int32"},
    Int64:         {Int64, IsInteger, "int64"},
    Uint:          {Uint, IsInteger | IsUnsigned, "uint"},
    Uint8:         {Uint8, IsInteger | IsUnsigned, "uint8"},
    Uint16:        {Uint16, IsInteger | IsUnsigned, "uint16"},
    Uint32:        {Uint32, IsInteger | IsUnsigned, "uint32"},
    Uint64:        {Uint64, IsInteger | IsUnsigned, "uint64"},
    Uintptr:       {Uintptr, IsInteger | IsUnsigned, "uintptr"},
    Float32:       {Float32, IsFloat, "float32"},
    Float64:       {Float64, IsFloat, "float64"},
    Complex64:     {Complex64, IsComplex, "complex64"},
    Complex128:    {Complex128, IsComplex, "complex128"},
    String:        {String, IsString, "string"},
    UnsafePointer: {UnsafePointer, 0, "Pointer"},

    UntypedBool:    {UntypedBool, IsBoolean | IsUntyped, "untyped bool"},
    UntypedInt:     {UntypedInt, IsInteger | IsUntyped, "untyped int"},
    UntypedRune:    {UntypedRune, IsInteger | IsUntyped, "untyped rune"},
    UntypedFloat:   {UntypedFloat, IsFloat | IsUntyped, "untyped float"},
    UntypedComplex: {UntypedComplex, IsComplex | IsUntyped, "untyped complex"},
    UntypedString:  {UntypedString, IsString | IsUntyped, "untyped string"},
    UntypedNil:     {UntypedNil, IsUntyped, "untyped nil"},
}

func AssertableTo 1.5

func AssertableTo(V *Interface, T Type) bool

AssertableTo reports whether a value of type V can be asserted to have type T.

The behavior of AssertableTo is unspecified in three cases:

func AssignableTo 1.5

func AssignableTo(V, T Type) bool

AssignableTo reports whether a value of type V is assignable to a variable of type T.

The behavior of AssignableTo is unspecified if V or T is Typ[Invalid] or an uninstantiated generic type.

func CheckExpr 1.13

func CheckExpr(fset *token.FileSet, pkg *Package, pos token.Pos, expr ast.Expr, info *Info) (err error)

CheckExpr type checks the expression expr as if it had appeared at position pos of package pkg. Type information about the expression is recorded in info. The expression may be an identifier denoting an uninstantiated generic function or type.

If pkg == nil, the Universe scope is used and the provided position pos is ignored. If pkg != nil, and pos is invalid, the package scope is used. Otherwise, pos must belong to the package.

An error is returned if pos is not within the package or if the node cannot be type-checked.

Note: Eval and CheckExpr should not be used instead of running Check to compute types and values, but in addition to Check, as these functions ignore the context in which an expression is used (e.g., an assignment). Thus, top-level untyped constants will return an untyped type rather than the respective context-specific type.

func Comparable 1.5

func Comparable(T Type) bool

Comparable reports whether values of type T are comparable.

func ConvertibleTo 1.5

func ConvertibleTo(V, T Type) bool

ConvertibleTo reports whether a value of type V is convertible to a value of type T.

The behavior of ConvertibleTo is unspecified if V or T is Typ[Invalid] or an uninstantiated generic type.

func DefPredeclaredTestFuncs 1.5

func DefPredeclaredTestFuncs()

DefPredeclaredTestFuncs defines the assert and trace built-ins. These built-ins are intended for debugging and testing of this package only.

func ExprString 1.5

func ExprString(x ast.Expr) string

ExprString returns the (possibly shortened) string representation for x. Shortened representations are suitable for user interfaces but may not necessarily follow Go syntax.

func Id 1.5

func Id(pkg *Package, name string) string

Id returns name if it is exported, otherwise it returns the name qualified with the package path.

func Identical 1.5

func Identical(x, y Type) bool

Identical reports whether x and y are identical types. Receivers of Signature types are ignored.

Predicates such as Identical, Implements, and Satisfies assume that both operands belong to a consistent collection of symbols (Object values). For example, two Named types can be identical only if their Named.Obj methods return the same TypeName symbol. A collection of symbols is consistent if, for each logical package whose path is P, the creation of those symbols involved at most one call to NewPackage(P, ...). To ensure consistency, use a single Importer for all loaded packages and their dependencies. For more information, see https://github.com/golang/go/issues/57497.

func IdenticalIgnoreTags 1.8

func IdenticalIgnoreTags(x, y Type) bool

IdenticalIgnoreTags reports whether x and y are identical types if tags are ignored. Receivers of Signature types are ignored.

func Implements 1.5

func Implements(V Type, T *Interface) bool

Implements reports whether type V implements interface T.

The behavior of Implements is unspecified if V is Typ[Invalid] or an uninstantiated generic type.

func IsInterface 1.5

func IsInterface(t Type) bool

IsInterface reports whether t is an interface type.

func ObjectString 1.5

func ObjectString(obj Object, qf Qualifier) string

ObjectString returns the string form of obj. The Qualifier controls the printing of package-level objects, and may be nil.

func Satisfies 1.20

func Satisfies(V Type, T *Interface) bool

Satisfies reports whether type V satisfies the constraint T.

The behavior of Satisfies is unspecified if V is Typ[Invalid] or an uninstantiated generic type.

func SelectionString 1.5

func SelectionString(s *Selection, qf Qualifier) string

SelectionString returns the string form of s. The Qualifier controls the printing of package-level objects, and may be nil.

Examples:

"field (T) f int"
"method (T) f(X) Y"
"method expr (T) f(X) Y"

func TypeString 1.5

func TypeString(typ Type, qf Qualifier) string

TypeString returns the string representation of typ. The Qualifier controls the printing of package-level objects, and may be nil.

func WriteExpr 1.5

func WriteExpr(buf *bytes.Buffer, x ast.Expr)

WriteExpr writes the (possibly shortened) string representation for x to buf. Shortened representations are suitable for user interfaces but may not necessarily follow Go syntax.

func WriteSignature 1.5

func WriteSignature(buf *bytes.Buffer, sig *Signature, qf Qualifier)

WriteSignature writes the representation of the signature sig to buf, without a leading "func" keyword. The Qualifier controls the printing of package-level objects, and may be nil.

func WriteType 1.5

func WriteType(buf *bytes.Buffer, typ Type, qf Qualifier)

WriteType writes the string representation of typ to buf. The Qualifier controls the printing of package-level objects, and may be nil.

type Alias 1.22

An Alias represents an alias type. Whether or not Alias types are created is controlled by the gotypesalias setting with the GODEBUG environment variable. For gotypesalias=1, alias declarations produce an Alias type. Otherwise, the alias information is only in the type name, which points directly to the actual (aliased) type.

type Alias struct {
    // contains filtered or unexported fields
}

func NewAlias 1.22

func NewAlias(obj *TypeName, rhs Type) *Alias

NewAlias creates a new Alias type with the given type name and rhs. rhs must not be nil.

func (*Alias) Obj 1.22

func (a *Alias) Obj() *TypeName

Obj returns the type name for the declaration defining the alias type a. For instantiated types, this is same as the type name of the origin type.

func (*Alias) Origin 1.23

func (a *Alias) Origin() *Alias

Origin returns the generic Alias type of which a is an instance. If a is not an instance of a generic alias, Origin returns a.

func (*Alias) Rhs 1.23

func (a *Alias) Rhs() Type

Rhs returns the type R on the right-hand side of an alias declaration "type A = R", which may be another alias.

func (*Alias) SetTypeParams 1.23

func (a *Alias) SetTypeParams(tparams []*TypeParam)

SetTypeParams sets the type parameters of the alias type a. The alias a must not have type arguments.

func (*Alias) String 1.22

func (a *Alias) String() string

func (*Alias) TypeArgs 1.23

func (a *Alias) TypeArgs() *TypeList

TypeArgs returns the type arguments used to instantiate the Alias type. If a is not an instance of a generic alias, the result is nil.

func (*Alias) TypeParams 1.23

func (a *Alias) TypeParams() *TypeParamList

TypeParams returns the type parameters of the alias type a, or nil. A generic Alias and its instances have the same type parameters.

func (*Alias) Underlying 1.22

func (a *Alias) Underlying() Type

Underlying returns the underlying type of the alias type a, which is the underlying type of the aliased type. Underlying types are never Named, TypeParam, or Alias types.

type ArgumentError 1.18

An ArgumentError holds an error associated with an argument index.

type ArgumentError struct {
    Index int
    Err   error
}

func (*ArgumentError) Error 1.18

func (e *ArgumentError) Error() string

func (*ArgumentError) Unwrap 1.18

func (e *ArgumentError) Unwrap() error

type Array 1.5

An Array represents an array type.

type Array struct {
    // contains filtered or unexported fields
}

func NewArray 1.5

func NewArray(elem Type, len int64) *Array

NewArray returns a new array type for the given element type and length. A negative length indicates an unknown length.

func (*Array) Elem 1.5

func (a *Array) Elem() Type

Elem returns element type of array a.

func (*Array) Len 1.5

func (a *Array) Len() int64

Len returns the length of array a. A negative result indicates an unknown length.

func (*Array) String 1.5

func (a *Array) String() string

func (*Array) Underlying 1.5

func (a *Array) Underlying() Type

type Basic 1.5

A Basic represents a basic type.

type Basic struct {
    // contains filtered or unexported fields
}

func (*Basic) Info 1.5

func (b *Basic) Info() BasicInfo

Info returns information about properties of basic type b.

func (*Basic) Kind 1.5

func (b *Basic) Kind() BasicKind

Kind returns the kind of basic type b.

func (*Basic) Name 1.5

func (b *Basic) Name() string

Name returns the name of basic type b.

func (*Basic) String 1.5

func (b *Basic) String() string

func (*Basic) Underlying 1.5

func (b *Basic) Underlying() Type

type BasicInfo 1.5

BasicInfo is a set of flags describing properties of a basic type.

type BasicInfo int

Properties of basic types.

const (
    IsBoolean BasicInfo = 1 << iota
    IsInteger
    IsUnsigned
    IsFloat
    IsComplex
    IsString
    IsUntyped

    IsOrdered   = IsInteger | IsFloat | IsString
    IsNumeric   = IsInteger | IsFloat | IsComplex
    IsConstType = IsBoolean | IsNumeric | IsString
)

type BasicKind 1.5

BasicKind describes the kind of basic type.

type BasicKind int
const (
    Invalid BasicKind = iota // type is invalid

    // predeclared types
    Bool
    Int
    Int8
    Int16
    Int32
    Int64
    Uint
    Uint8
    Uint16
    Uint32
    Uint64
    Uintptr
    Float32
    Float64
    Complex64
    Complex128
    String
    UnsafePointer

    // types for untyped values
    UntypedBool
    UntypedInt
    UntypedRune
    UntypedFloat
    UntypedComplex
    UntypedString
    UntypedNil

    // aliases
    Byte = Uint8
    Rune = Int32
)

type Builtin 1.5

A Builtin represents a built-in function. Builtins don't have a valid type.

type Builtin struct {
    // contains filtered or unexported fields
}

func (*Builtin) Exported 1.5

func (obj *Builtin) Exported() bool

Exported reports whether the object is exported (starts with a capital letter). It doesn't take into account whether the object is in a local (function) scope or not.

func (*Builtin) Id 1.5

func (obj *Builtin) Id() string

Id is a wrapper for Id(obj.Pkg(), obj.Name()).

func (*Builtin) Name 1.5

func (obj *Builtin) Name() string

Name returns the object's (package-local, unqualified) name.

func (*Builtin) Parent 1.5

func (obj *Builtin) Parent() *Scope

Parent returns the scope in which the object is declared. The result is nil for methods and struct fields.

func (*Builtin) Pkg 1.5

func (obj *Builtin) Pkg() *Package

Pkg returns the package to which the object belongs. The result is nil for labels and objects in the Universe scope.

func (*Builtin) Pos 1.5

func (obj *Builtin) Pos() token.Pos

Pos returns the declaration position of the object's identifier.

func (*Builtin) String 1.5

func (obj *Builtin) String() string

func (*Builtin) Type 1.5

func (obj *Builtin) Type() Type

Type returns the object's type.

type Chan 1.5

A Chan represents a channel type.

type Chan struct {
    // contains filtered or unexported fields
}

func NewChan 1.5

func NewChan(dir ChanDir, elem Type) *Chan

NewChan returns a new channel type for the given direction and element type.

func (*Chan) Dir 1.5

func (c *Chan) Dir() ChanDir

Dir returns the direction of channel c.

func (*Chan) Elem 1.5

func (c *Chan) Elem() Type

Elem returns the element type of channel c.

func (*Chan) String 1.5

func (c *Chan) String() string

func (*Chan) Underlying 1.5

func (c *Chan) Underlying() Type

type ChanDir 1.5

A ChanDir value indicates a channel direction.

type ChanDir int

The direction of a channel is indicated by one of these constants.

const (
    SendRecv ChanDir = iota
    SendOnly
    RecvOnly
)

type Checker 1.5

A Checker maintains the state of the type checker. It must be created with NewChecker.

type Checker struct {
    *Info
    // contains filtered or unexported fields
}

func NewChecker 1.5

func NewChecker(conf *Config, fset *token.FileSet, pkg *Package, info *Info) *Checker

NewChecker returns a new Checker instance for a given package. Package files may be added incrementally via checker.Files.

func (*Checker) Files 1.5

func (check *Checker) Files(files []*ast.File) (err error)

Files checks the provided files as part of the checker's package.

type Config 1.5

A Config specifies the configuration for type checking. The zero value for Config is a ready-to-use default configuration.

type Config struct {
    // Context is the context used for resolving global identifiers. If nil, the
    // type checker will initialize this field with a newly created context.
    Context *Context // Go 1.18

    // GoVersion describes the accepted Go language version. The string must
    // start with a prefix of the form "go%d.%d" (e.g. "go1.20", "go1.21rc1", or
    // "go1.21.0") or it must be empty; an empty string disables Go language
    // version checks. If the format is invalid, invoking the type checker will
    // result in an error.
    GoVersion string // Go 1.18

    // If IgnoreFuncBodies is set, function bodies are not
    // type-checked.
    IgnoreFuncBodies bool

    // If FakeImportC is set, `import "C"` (for packages requiring Cgo)
    // declares an empty "C" package and errors are omitted for qualified
    // identifiers referring to package C (which won't find an object).
    // This feature is intended for the standard library cmd/api tool.
    //
    // Caution: Effects may be unpredictable due to follow-on errors.
    //          Do not use casually!
    FakeImportC bool

    // If Error != nil, it is called with each error found
    // during type checking; err has dynamic type Error.
    // Secondary errors (for instance, to enumerate all types
    // involved in an invalid recursive type declaration) have
    // error strings that start with a '\t' character.
    // If Error == nil, type-checking stops with the first
    // error found.
    Error func(err error)

    // An importer is used to import packages referred to from
    // import declarations.
    // If the installed importer implements ImporterFrom, the type
    // checker calls ImportFrom instead of Import.
    // The type checker reports an error if an importer is needed
    // but none was installed.
    Importer Importer

    // If Sizes != nil, it provides the sizing functions for package unsafe.
    // Otherwise SizesFor("gc", "amd64") is used instead.
    Sizes Sizes

    // If DisableUnusedImportCheck is set, packages are not checked
    // for unused imports.
    DisableUnusedImportCheck bool
    // contains filtered or unexported fields
}

func (*Config) Check 1.5

func (conf *Config) Check(path string, fset *token.FileSet, files []*ast.File, info *Info) (*Package, error)

Check type-checks a package and returns the resulting package object and the first error if any. Additionally, if info != nil, Check populates each of the non-nil maps in the Info struct.

The package is marked as complete if no errors occurred, otherwise it is incomplete. See [Config.Error] for controlling behavior in the presence of errors.

The package is specified by a list of *ast.Files and corresponding file set, and the package path the package is identified with. The clean path must not be empty or dot (".").

type Const 1.5

A Const represents a declared constant.

type Const struct {
    // contains filtered or unexported fields
}

func NewConst 1.5

func NewConst(pos token.Pos, pkg *Package, name string, typ Type, val constant.Value) *Const

NewConst returns a new constant with value val. The remaining arguments set the attributes found with all Objects.

func (*Const) Exported 1.5

func (obj *Const) Exported() bool

Exported reports whether the object is exported (starts with a capital letter). It doesn't take into account whether the object is in a local (function) scope or not.

func (*Const) Id 1.5

func (obj *Const) Id() string

Id is a wrapper for Id(obj.Pkg(), obj.Name()).

func (*Const) Name 1.5

func (obj *Const) Name() string

Name returns the object's (package-local, unqualified) name.

func (*Const) Parent 1.5

func (obj *Const) Parent() *Scope

Parent returns the scope in which the object is declared. The result is nil for methods and struct fields.

func (*Const) Pkg 1.5

func (obj *Const) Pkg() *Package

Pkg returns the package to which the object belongs. The result is nil for labels and objects in the Universe scope.

func (*Const) Pos 1.5

func (obj *Const) Pos() token.Pos

Pos returns the declaration position of the object's identifier.

func (*Const) String 1.5

func (obj *Const) String() string

func (*Const) Type 1.5

func (obj *Const) Type() Type

Type returns the object's type.

func (*Const) Val 1.5

func (obj *Const) Val() constant.Value

Val returns the constant's value.

type Context 1.18

A Context is an opaque type checking context. It may be used to share identical type instances across type-checked packages or calls to Instantiate. Contexts are safe for concurrent use.

The use of a shared context does not guarantee that identical instances are deduplicated in all cases.

type Context struct {
    // contains filtered or unexported fields
}

func NewContext 1.18

func NewContext() *Context

NewContext creates a new Context.

type Error 1.5

An Error describes a type-checking error; it implements the error interface. A "soft" error is an error that still permits a valid interpretation of a package (such as "unused variable"); "hard" errors may lead to unpredictable behavior if ignored.

type Error struct {
    Fset *token.FileSet // file set for interpretation of Pos
    Pos  token.Pos      // error position
    Msg  string         // error message
    Soft bool           // if set, error is "soft"
    // contains filtered or unexported fields
}

func (Error) Error 1.5

func (err Error) Error() string

Error returns an error string formatted as follows: filename:line:column: message

type Func 1.5

A Func represents a declared function, concrete method, or abstract (interface) method. Its Type() is always a *Signature. An abstract method may belong to many interfaces due to embedding.

type Func struct {
    // contains filtered or unexported fields
}

func MissingMethod 1.5

func MissingMethod(V Type, T *Interface, static bool) (method *Func, wrongType bool)

MissingMethod returns (nil, false) if V implements T, otherwise it returns a missing method required by T and whether it is missing or just has the wrong type: either a pointer receiver or wrong signature.

For non-interface types V, or if static is set, V implements T if all methods of T are present in V. Otherwise (V is an interface and static is not set), MissingMethod only checks that methods of T which are also present in V have matching types (e.g., for a type assertion x.(T) where x is of interface type V).

func NewFunc 1.5

func NewFunc(pos token.Pos, pkg *Package, name string, sig *Signature) *Func

NewFunc returns a new function with the given signature, representing the function's type.

func (*Func) Exported 1.5

func (obj *Func) Exported() bool

Exported reports whether the object is exported (starts with a capital letter). It doesn't take into account whether the object is in a local (function) scope or not.

func (*Func) FullName 1.5

func (obj *Func) FullName() string

FullName returns the package- or receiver-type-qualified name of function or method obj.

func (*Func) Id 1.5

func (obj *Func) Id() string

Id is a wrapper for Id(obj.Pkg(), obj.Name()).

func (*Func) Name 1.5

func (obj *Func) Name() string

Name returns the object's (package-local, unqualified) name.

func (*Func) Origin 1.19

func (obj *Func) Origin() *Func

Origin returns the canonical Func for its receiver, i.e. the Func object recorded in Info.Defs.

For synthetic functions created during instantiation (such as methods on an instantiated Named type or interface methods that depend on type arguments), this will be the corresponding Func on the generic (uninstantiated) type. For all other Funcs Origin returns the receiver.

func (*Func) Parent 1.5

func (obj *Func) Parent() *Scope

Parent returns the scope in which the object is declared. The result is nil for methods and struct fields.

func (*Func) Pkg 1.5

func (obj *Func) Pkg() *Package

Pkg returns the package to which the function belongs.

The result is nil for methods of types in the Universe scope, like method Error of the error built-in interface type.

func (*Func) Pos 1.5

func (obj *Func) Pos() token.Pos

Pos returns the declaration position of the object's identifier.

func (*Func) Scope 1.5

func (obj *Func) Scope() *Scope

Scope returns the scope of the function's body block. The result is nil for imported or instantiated functions and methods (but there is also no mechanism to get to an instantiated function).

func (*Func) Signature 1.23

func (obj *Func) Signature() *Signature

Signature returns the signature (type) of the function or method.

func (*Func) String 1.5

func (obj *Func) String() string

func (*Func) Type 1.5

func (obj *Func) Type() Type

Type returns the object's type.

type ImportMode 1.6

ImportMode is reserved for future use.

type ImportMode int

type Importer 1.5

An Importer resolves import paths to Packages.

CAUTION: This interface does not support the import of locally vendored packages. See https://golang.org/s/go15vendor. If possible, external implementations should implement ImporterFrom.

type Importer interface {
    // Import returns the imported package for the given import path.
    // The semantics is like for ImporterFrom.ImportFrom except that
    // dir and mode are ignored (since they are not present).
    Import(path string) (*Package, error)
}

type ImporterFrom 1.6

An ImporterFrom resolves import paths to packages; it supports vendoring per https://golang.org/s/go15vendor. Use go/importer to obtain an ImporterFrom implementation.

type ImporterFrom interface {
    // Importer is present for backward-compatibility. Calling
    // Import(path) is the same as calling ImportFrom(path, "", 0);
    // i.e., locally vendored packages may not be found.
    // The types package does not call Import if an ImporterFrom
    // is present.
    Importer

    // ImportFrom returns the imported package for the given import
    // path when imported by a package file located in dir.
    // If the import failed, besides returning an error, ImportFrom
    // is encouraged to cache and return a package anyway, if one
    // was created. This will reduce package inconsistencies and
    // follow-on type checker errors due to the missing package.
    // The mode value must be 0; it is reserved for future use.
    // Two calls to ImportFrom with the same path and dir must
    // return the same package.
    ImportFrom(path, dir string, mode ImportMode) (*Package, error)
}

type Info 1.5

Info holds result type information for a type-checked package. Only the information for which a map is provided is collected. If the package has type errors, the collected information may be incomplete.

type Info struct {
    // Types maps expressions to their types, and for constant
    // expressions, also their values. Invalid expressions are
    // omitted.
    //
    // For (possibly parenthesized) identifiers denoting built-in
    // functions, the recorded signatures are call-site specific:
    // if the call result is not a constant, the recorded type is
    // an argument-specific signature. Otherwise, the recorded type
    // is invalid.
    //
    // The Types map does not record the type of every identifier,
    // only those that appear where an arbitrary expression is
    // permitted. For instance, the identifier f in a selector
    // expression x.f is found only in the Selections map, the
    // identifier z in a variable declaration 'var z int' is found
    // only in the Defs map, and identifiers denoting packages in
    // qualified identifiers are collected in the Uses map.
    Types map[ast.Expr]TypeAndValue

    // Instances maps identifiers denoting generic types or functions to their
    // type arguments and instantiated type.
    //
    // For example, Instances will map the identifier for 'T' in the type
    // instantiation T[int, string] to the type arguments [int, string] and
    // resulting instantiated *Named type. Given a generic function
    // func F[A any](A), Instances will map the identifier for 'F' in the call
    // expression F(int(1)) to the inferred type arguments [int], and resulting
    // instantiated *Signature.
    //
    // Invariant: Instantiating Uses[id].Type() with Instances[id].TypeArgs
    // results in an equivalent of Instances[id].Type.
    Instances map[*ast.Ident]Instance // Go 1.18

    // Defs maps identifiers to the objects they define (including
    // package names, dots "." of dot-imports, and blank "_" identifiers).
    // For identifiers that do not denote objects (e.g., the package name
    // in package clauses, or symbolic variables t in t := x.(type) of
    // type switch headers), the corresponding objects are nil.
    //
    // For an embedded field, Defs returns the field *Var it defines.
    //
    // Invariant: Defs[id] == nil || Defs[id].Pos() == id.Pos()
    Defs map[*ast.Ident]Object

    // Uses maps identifiers to the objects they denote.
    //
    // For an embedded field, Uses returns the *TypeName it denotes.
    //
    // Invariant: Uses[id].Pos() != id.Pos()
    Uses map[*ast.Ident]Object

    // Implicits maps nodes to their implicitly declared objects, if any.
    // The following node and object types may appear:
    //
    //     node               declared object
    //
    //     *ast.ImportSpec    *PkgName for imports without renames
    //     *ast.CaseClause    type-specific *Var for each type switch case clause (incl. default)
    //     *ast.Field         anonymous parameter *Var (incl. unnamed results)
    //
    Implicits map[ast.Node]Object

    // Selections maps selector expressions (excluding qualified identifiers)
    // to their corresponding selections.
    Selections map[*ast.SelectorExpr]*Selection

    // Scopes maps ast.Nodes to the scopes they define. Package scopes are not
    // associated with a specific node but with all files belonging to a package.
    // Thus, the package scope can be found in the type-checked Package object.
    // Scopes nest, with the Universe scope being the outermost scope, enclosing
    // the package scope, which contains (one or more) files scopes, which enclose
    // function scopes which in turn enclose statement and function literal scopes.
    // Note that even though package-level functions are declared in the package
    // scope, the function scopes are embedded in the file scope of the file
    // containing the function declaration.
    //
    // The Scope of a function contains the declarations of any
    // type parameters, parameters, and named results, plus any
    // local declarations in the body block.
    // It is coextensive with the complete extent of the
    // function's syntax ([*ast.FuncDecl] or [*ast.FuncLit]).
    // The Scopes mapping does not contain an entry for the
    // function body ([*ast.BlockStmt]); the function's scope is
    // associated with the [*ast.FuncType].
    //
    // The following node types may appear in Scopes:
    //
    //     *ast.File
    //     *ast.FuncType
    //     *ast.TypeSpec
    //     *ast.BlockStmt
    //     *ast.IfStmt
    //     *ast.SwitchStmt
    //     *ast.TypeSwitchStmt
    //     *ast.CaseClause
    //     *ast.CommClause
    //     *ast.ForStmt
    //     *ast.RangeStmt
    //
    Scopes map[ast.Node]*Scope

    // InitOrder is the list of package-level initializers in the order in which
    // they must be executed. Initializers referring to variables related by an
    // initialization dependency appear in topological order, the others appear
    // in source order. Variables without an initialization expression do not
    // appear in this list.
    InitOrder []*Initializer

    // FileVersions maps a file to its Go version string.
    // If the file doesn't specify a version, the reported
    // string is Config.GoVersion.
    // Version strings begin with “go”, like “go1.21”, and
    // are suitable for use with the [go/version] package.
    FileVersions map[*ast.File]string // Go 1.22
}

Example

ExampleInfo prints various facts recorded by the type checker in a types.Info struct: definitions of and references to each named object, and the type, value, and mode of every expression in the package.

Code:

// Parse a single source file.
const input = `
package fib

type S string

var a, b, c = len(b), S(c), "hello"

func fib(x int) int {
    if x < 2 {
        return x
    }
    return fib(x-1) - fib(x-2)
}`
// We need a specific fileset in this test below for positions.
// Cannot use typecheck helper.
fset := token.NewFileSet()
f := mustParse(fset, input)

// Type-check the package.
// We create an empty map for each kind of input
// we're interested in, and Check populates them.
info := types.Info{
    Types: make(map[ast.Expr]types.TypeAndValue),
    Defs:  make(map[*ast.Ident]types.Object),
    Uses:  make(map[*ast.Ident]types.Object),
}
var conf types.Config
pkg, err := conf.Check("fib", fset, []*ast.File{f}, &info)
if err != nil {
    log.Fatal(err)
}

// Print package-level variables in initialization order.
fmt.Printf("InitOrder: %v\n\n", info.InitOrder)

// For each named object, print the line and
// column of its definition and each of its uses.
fmt.Println("Defs and Uses of each named object:")
usesByObj := make(map[types.Object][]string)
for id, obj := range info.Uses {
    posn := fset.Position(id.Pos())
    lineCol := fmt.Sprintf("%d:%d", posn.Line, posn.Column)
    usesByObj[obj] = append(usesByObj[obj], lineCol)
}
var items []string
for obj, uses := range usesByObj {
    slices.Sort(uses)
    item := fmt.Sprintf("%s:\n  defined at %s\n  used at %s",
        types.ObjectString(obj, types.RelativeTo(pkg)),
        fset.Position(obj.Pos()),
        strings.Join(uses, ", "))
    items = append(items, item)
}
slices.Sort(items) // sort by line:col, in effect
fmt.Println(strings.Join(items, "\n"))
fmt.Println()

fmt.Println("Types and Values of each expression:")
items = nil
for expr, tv := range info.Types {
    var buf strings.Builder
    posn := fset.Position(expr.Pos())
    tvstr := tv.Type.String()
    if tv.Value != nil {
        tvstr += " = " + tv.Value.String()
    }
    // line:col | expr | mode : type = value
    fmt.Fprintf(&buf, "%2d:%2d | %-19s | %-7s : %s",
        posn.Line, posn.Column, exprString(fset, expr),
        mode(tv), tvstr)
    items = append(items, buf.String())
}
slices.Sort(items)
fmt.Println(strings.Join(items, "\n"))

Output:

InitOrder: [c = "hello" b = S(c) a = len(b)]

Defs and Uses of each named object:
builtin len:
  defined at -
  used at 6:15
func fib(x int) int:
  defined at fib:8:6
  used at 12:20, 12:9
type S string:
  defined at fib:4:6
  used at 6:23
type int:
  defined at -
  used at 8:12, 8:17
type string:
  defined at -
  used at 4:8
var b S:
  defined at fib:6:8
  used at 6:19
var c string:
  defined at fib:6:11
  used at 6:25
var x int:
  defined at fib:8:10
  used at 10:10, 12:13, 12:24, 9:5

Types and Values of each expression:
 4: 8 | string              | type    : string
 6:15 | len                 | builtin : func(fib.S) int
 6:15 | len(b)              | value   : int
 6:19 | b                   | var     : fib.S
 6:23 | S                   | type    : fib.S
 6:23 | S(c)                | value   : fib.S
 6:25 | c                   | var     : string
 6:29 | "hello"             | value   : string = "hello"
 8:12 | int                 | type    : int
 8:17 | int                 | type    : int
 9: 5 | x                   | var     : int
 9: 5 | x < 2               | value   : untyped bool
 9: 9 | 2                   | value   : int = 2
10:10 | x                   | var     : int
12: 9 | fib                 | value   : func(x int) int
12: 9 | fib(x - 1)          | value   : int
12: 9 | fib(x-1) - fib(x-2) | value   : int
12:13 | x                   | var     : int
12:13 | x - 1               | value   : int
12:15 | 1                   | value   : int = 1
12:20 | fib                 | value   : func(x int) int
12:20 | fib(x - 2)          | value   : int
12:24 | x                   | var     : int
12:24 | x - 2               | value   : int
12:26 | 2                   | value   : int = 2

func (*Info) ObjectOf 1.5

func (info *Info) ObjectOf(id *ast.Ident) Object

ObjectOf returns the object denoted by the specified id, or nil if not found.

If id is an embedded struct field, Info.ObjectOf returns the field (*Var) it defines, not the type (*TypeName) it uses.

Precondition: the Uses and Defs maps are populated.

func (*Info) PkgNameOf 1.22

func (info *Info) PkgNameOf(imp *ast.ImportSpec) *PkgName

PkgNameOf returns the local package name defined by the import, or nil if not found.

For dot-imports, the package name is ".".

Precondition: the Defs and Implicts maps are populated.

func (*Info) TypeOf 1.5

func (info *Info) TypeOf(e ast.Expr) Type

TypeOf returns the type of expression e, or nil if not found. Precondition: the Types, Uses and Defs maps are populated.

type Initializer 1.5

An Initializer describes a package-level variable, or a list of variables in case of a multi-valued initialization expression, and the corresponding initialization expression.

type Initializer struct {
    Lhs []*Var // var Lhs = Rhs
    Rhs ast.Expr
}

func (*Initializer) String 1.5

func (init *Initializer) String() string

type Instance 1.18

Instance reports the type arguments and instantiated type for type and function instantiations. For type instantiations, Type will be of dynamic type *Named. For function instantiations, Type will be of dynamic type *Signature.

type Instance struct {
    TypeArgs *TypeList
    Type     Type
}

type Interface 1.5

An Interface represents an interface type.

type Interface struct {
    // contains filtered or unexported fields
}

func NewInterface 1.5

func NewInterface(methods []*Func, embeddeds []*Named) *Interface

NewInterface returns a new interface for the given methods and embedded types. NewInterface takes ownership of the provided methods and may modify their types by setting missing receivers.

Deprecated: Use NewInterfaceType instead which allows arbitrary embedded types.

func NewInterfaceType 1.11

func NewInterfaceType(methods []*Func, embeddeds []Type) *Interface

NewInterfaceType returns a new interface for the given methods and embedded types. NewInterfaceType takes ownership of the provided methods and may modify their types by setting missing receivers.

To avoid race conditions, the interface's type set should be computed before concurrent use of the interface, by explicitly calling Complete.

func (*Interface) Complete 1.5

func (t *Interface) Complete() *Interface

Complete computes the interface's type set. It must be called by users of NewInterfaceType and NewInterface after the interface's embedded types are fully defined and before using the interface type in any way other than to form other types. The interface must not contain duplicate methods or a panic occurs. Complete returns the receiver.

Interface types that have been completed are safe for concurrent use.

func (*Interface) Embedded 1.5

func (t *Interface) Embedded(i int) *Named

Embedded returns the i'th embedded defined (*Named) type of interface t for 0 <= i < t.NumEmbeddeds(). The result is nil if the i'th embedded type is not a defined type.

Deprecated: Use Interface.EmbeddedType which is not restricted to defined (*Named) types.

func (*Interface) EmbeddedType 1.11

func (t *Interface) EmbeddedType(i int) Type

EmbeddedType returns the i'th embedded type of interface t for 0 <= i < t.NumEmbeddeds().

func (*Interface) Empty 1.5

func (t *Interface) Empty() bool

Empty reports whether t is the empty interface.

func (*Interface) ExplicitMethod 1.5

func (t *Interface) ExplicitMethod(i int) *Func

ExplicitMethod returns the i'th explicitly declared method of interface t for 0 <= i < t.NumExplicitMethods(). The methods are ordered by their unique Id.

func (*Interface) IsComparable 1.18

func (t *Interface) IsComparable() bool

IsComparable reports whether each type in interface t's type set is comparable.

func (*Interface) IsImplicit 1.18

func (t *Interface) IsImplicit() bool

IsImplicit reports whether the interface t is a wrapper for a type set literal.

func (*Interface) IsMethodSet 1.18

func (t *Interface) IsMethodSet() bool

IsMethodSet reports whether the interface t is fully described by its method set.

func (*Interface) MarkImplicit 1.18

func (t *Interface) MarkImplicit()

MarkImplicit marks the interface t as implicit, meaning this interface corresponds to a constraint literal such as ~T or A|B without explicit interface embedding. MarkImplicit should be called before any concurrent use of implicit interfaces.

func (*Interface) Method 1.5

func (t *Interface) Method(i int) *Func

Method returns the i'th method of interface t for 0 <= i < t.NumMethods(). The methods are ordered by their unique Id.

func (*Interface) NumEmbeddeds 1.5

func (t *Interface) NumEmbeddeds() int

NumEmbeddeds returns the number of embedded types in interface t.

func (*Interface) NumExplicitMethods 1.5

func (t *Interface) NumExplicitMethods() int

NumExplicitMethods returns the number of explicitly declared methods of interface t.

func (*Interface) NumMethods 1.5

func (t *Interface) NumMethods() int

NumMethods returns the total number of methods of interface t.

func (*Interface) String 1.5

func (t *Interface) String() string

func (*Interface) Underlying 1.5

func (t *Interface) Underlying() Type

type Label 1.5

A Label represents a declared label. Labels don't have a type.

type Label struct {
    // contains filtered or unexported fields
}

func NewLabel 1.5

func NewLabel(pos token.Pos, pkg *Package, name string) *Label

NewLabel returns a new label.

func (*Label) Exported 1.5

func (obj *Label) Exported() bool

Exported reports whether the object is exported (starts with a capital letter). It doesn't take into account whether the object is in a local (function) scope or not.

func (*Label) Id 1.5

func (obj *Label) Id() string

Id is a wrapper for Id(obj.Pkg(), obj.Name()).

func (*Label) Name 1.5

func (obj *Label) Name() string

Name returns the object's (package-local, unqualified) name.

func (*Label) Parent 1.5

func (obj *Label) Parent() *Scope

Parent returns the scope in which the object is declared. The result is nil for methods and struct fields.

func (*Label) Pkg 1.5

func (obj *Label) Pkg() *Package

Pkg returns the package to which the object belongs. The result is nil for labels and objects in the Universe scope.

func (*Label) Pos 1.5

func (obj *Label) Pos() token.Pos

Pos returns the declaration position of the object's identifier.

func (*Label) String 1.5

func (obj *Label) String() string

func (*Label) Type 1.5

func (obj *Label) Type() Type

Type returns the object's type.

type Map 1.5

A Map represents a map type.

type Map struct {
    // contains filtered or unexported fields
}

func NewMap 1.5

func NewMap(key, elem Type) *Map

NewMap returns a new map for the given key and element types.

func (*Map) Elem 1.5

func (m *Map) Elem() Type

Elem returns the element type of map m.

func (*Map) Key 1.5

func (m *Map) Key() Type

Key returns the key type of map m.

func (*Map) String 1.5

func (t *Map) String() string

func (*Map) Underlying 1.5

func (t *Map) Underlying() Type

type MethodSet 1.5

A MethodSet is an ordered set of concrete or abstract (interface) methods; a method is a MethodVal selection, and they are ordered by ascending m.Obj().Id(). The zero value for a MethodSet is a ready-to-use empty method set.

type MethodSet struct {
    // contains filtered or unexported fields
}

Example

ExampleMethodSet prints the method sets of various types.

Method set of temperature.Celsius:
method (temperature.Celsius) String() string

Method set of *temperature.Celsius:
method (*temperature.Celsius) SetF(f float64)
method (*temperature.Celsius) String() string

Method set of temperature.S:
MethodSet {}

func NewMethodSet 1.5

func NewMethodSet(T Type) *MethodSet

NewMethodSet returns the method set for the given type T. It always returns a non-nil method set, even if it is empty.

func (*MethodSet) At 1.5

func (s *MethodSet) At(i int) *Selection

At returns the i'th method in s for 0 <= i < s.Len().

func (*MethodSet) Len 1.5

func (s *MethodSet) Len() int

Len returns the number of methods in s.

func (*MethodSet) Lookup 1.5

func (s *MethodSet) Lookup(pkg *Package, name string) *Selection

Lookup returns the method with matching package and name, or nil if not found.

func (*MethodSet) String 1.5

func (s *MethodSet) String() string

type Named 1.5

A Named represents a named (defined) type.

type Named struct {
    // contains filtered or unexported fields
}

func NewNamed 1.5

func NewNamed(obj *TypeName, underlying Type, methods []*Func) *Named

NewNamed returns a new named type for the given type name, underlying type, and associated methods. If the given type name obj doesn't have a type yet, its type is set to the returned named type. The underlying type must not be a *Named.

func (*Named) AddMethod 1.5

func (t *Named) AddMethod(m *Func)

AddMethod adds method m unless it is already in the method list. The method must be in the same package as t, and t must not have type arguments.

func (*Named) Method 1.5

func (t *Named) Method(i int) *Func

Method returns the i'th method of named type t for 0 <= i < t.NumMethods().

For an ordinary or instantiated type t, the receiver base type of this method is the named type t. For an uninstantiated generic type t, each method receiver is instantiated with its receiver type parameters.

Methods are numbered deterministically: given the same list of source files presented to the type checker, or the same sequence of NewMethod and AddMethod calls, the mapping from method index to corresponding method remains the same. But the specific ordering is not specified and must not be relied on as it may change in the future.

func (*Named) NumMethods 1.5

func (t *Named) NumMethods() int

NumMethods returns the number of explicit methods defined for t.

func (*Named) Obj 1.5

func (t *Named) Obj() *TypeName

Obj returns the type name for the declaration defining the named type t. For instantiated types, this is same as the type name of the origin type.

func (*Named) Origin 1.18

func (t *Named) Origin() *Named

Origin returns the generic type from which the named type t is instantiated. If t is not an instantiated type, the result is t.

func (*Named) SetTypeParams 1.18

func (t *Named) SetTypeParams(tparams []*TypeParam)

SetTypeParams sets the type parameters of the named type t. t must not have type arguments.

func (*Named) SetUnderlying 1.5

func (t *Named) SetUnderlying(underlying Type)

SetUnderlying sets the underlying type and marks t as complete. t must not have type arguments.

func (*Named) String 1.5

func (t *Named) String() string

func (*Named) TypeArgs 1.18

func (t *Named) TypeArgs() *TypeList

TypeArgs returns the type arguments used to instantiate the named type t.

func (*Named) TypeParams 1.18

func (t *Named) TypeParams() *TypeParamList

TypeParams returns the type parameters of the named type t, or nil. The result is non-nil for an (originally) generic type even if it is instantiated.

func (*Named) Underlying 1.5

func (t *Named) Underlying() Type

Underlying returns the underlying type of the named type t, resolving all forwarding declarations. Underlying types are never Named, TypeParam, or Alias types.

type Nil 1.5

Nil represents the predeclared value nil.

type Nil struct {
    // contains filtered or unexported fields
}

func (*Nil) Exported 1.5

func (obj *Nil) Exported() bool

Exported reports whether the object is exported (starts with a capital letter). It doesn't take into account whether the object is in a local (function) scope or not.

func (*Nil) Id 1.5

func (obj *Nil) Id() string

Id is a wrapper for Id(obj.Pkg(), obj.Name()).

func (*Nil) Name 1.5

func (obj *Nil) Name() string

Name returns the object's (package-local, unqualified) name.

func (*Nil) Parent 1.5

func (obj *Nil) Parent() *Scope

Parent returns the scope in which the object is declared. The result is nil for methods and struct fields.

func (*Nil) Pkg 1.5

func (obj *Nil) Pkg() *Package

Pkg returns the package to which the object belongs. The result is nil for labels and objects in the Universe scope.

func (*Nil) Pos 1.5

func (obj *Nil) Pos() token.Pos

Pos returns the declaration position of the object's identifier.

func (*Nil) String 1.5

func (obj *Nil) String() string

func (*Nil) Type 1.5

func (obj *Nil) Type() Type

Type returns the object's type.

type Object 1.5

An Object describes a named language entity such as a package, constant, type, variable, function (incl. methods), or label. All objects implement the Object interface.

type Object interface {
    Parent() *Scope // scope in which this object is declared; nil for methods and struct fields
    Pos() token.Pos // position of object identifier in declaration
    Pkg() *Package  // package to which this object belongs; nil for labels and objects in the Universe scope
    Name() string   // package local object name
    Type() Type     // object type
    Exported() bool // reports whether the name starts with a capital letter
    Id() string     // object name if exported, qualified name if not exported (see func Id)

    // String returns a human-readable string of the object.
    String() string
    // contains filtered or unexported methods
}

func LookupFieldOrMethod 1.5

func LookupFieldOrMethod(T Type, addressable bool, pkg *Package, name string) (obj Object, index []int, indirect bool)

LookupFieldOrMethod looks up a field or method with given package and name in T and returns the corresponding *Var or *Func, an index sequence, and a bool indicating if there were any pointer indirections on the path to the field or method. If addressable is set, T is the type of an addressable variable (only matters for method lookups). T must not be nil.

The last index entry is the field or method index in the (possibly embedded) type where the entry was found, either:

  1. the list of declared methods of a named type; or
  2. the list of all methods (method set) of an interface type; or
  3. the list of fields of a struct type.

The earlier index entries are the indices of the embedded struct fields traversed to get to the found entry, starting at depth 0.

If no entry is found, a nil object is returned. In this case, the returned index and indirect values have the following meaning:

type Package 1.5

A Package describes a Go package.

type Package struct {
    // contains filtered or unexported fields
}

The Unsafe package is the package returned by an importer for the import path "unsafe".

var Unsafe *Package

func NewPackage 1.5

func NewPackage(path, name string) *Package

NewPackage returns a new Package for the given package path and name. The package is not complete and contains no explicit imports.

func (*Package) Complete 1.5

func (pkg *Package) Complete() bool

A package is complete if its scope contains (at least) all exported objects; otherwise it is incomplete.

func (*Package) GoVersion 1.21

func (pkg *Package) GoVersion() string

GoVersion returns the minimum Go version required by this package. If the minimum version is unknown, GoVersion returns the empty string. Individual source files may specify a different minimum Go version, as reported in the go/ast.File.GoVersion field.

func (*Package) Imports 1.5

func (pkg *Package) Imports() []*Package

Imports returns the list of packages directly imported by pkg; the list is in source order.

If pkg was loaded from export data, Imports includes packages that provide package-level objects referenced by pkg. This may be more or less than the set of packages directly imported by pkg's source code.

If pkg uses cgo and the FakeImportC configuration option was enabled, the imports list may contain a fake "C" package.

func (*Package) MarkComplete 1.5

func (pkg *Package) MarkComplete()

MarkComplete marks a package as complete.

func (*Package) Name 1.5

func (pkg *Package) Name() string

Name returns the package name.

func (*Package) Path 1.5

func (pkg *Package) Path() string

Path returns the package path.

func (*Package) Scope 1.5

func (pkg *Package) Scope() *Scope

Scope returns the (complete or incomplete) package scope holding the objects declared at package level (TypeNames, Consts, Vars, and Funcs). For a nil pkg receiver, Scope returns the Universe scope.

func (*Package) SetImports 1.5

func (pkg *Package) SetImports(list []*Package)

SetImports sets the list of explicitly imported packages to list. It is the caller's responsibility to make sure list elements are unique.

func (*Package) SetName 1.6

func (pkg *Package) SetName(name string)

SetName sets the package name.

func (*Package) String 1.5

func (pkg *Package) String() string

type PkgName 1.5

A PkgName represents an imported Go package. PkgNames don't have a type.

type PkgName struct {
    // contains filtered or unexported fields
}

func NewPkgName 1.5

func NewPkgName(pos token.Pos, pkg *Package, name string, imported *Package) *PkgName

NewPkgName returns a new PkgName object representing an imported package. The remaining arguments set the attributes found with all Objects.

func (*PkgName) Exported 1.5

func (obj *PkgName) Exported() bool

Exported reports whether the object is exported (starts with a capital letter). It doesn't take into account whether the object is in a local (function) scope or not.

func (*PkgName) Id 1.5

func (obj *PkgName) Id() string

Id is a wrapper for Id(obj.Pkg(), obj.Name()).

func (*PkgName) Imported 1.5

func (obj *PkgName) Imported() *Package

Imported returns the package that was imported. It is distinct from Pkg(), which is the package containing the import statement.

func (*PkgName) Name 1.5

func (obj *PkgName) Name() string

Name returns the object's (package-local, unqualified) name.

func (*PkgName) Parent 1.5

func (obj *PkgName) Parent() *Scope

Parent returns the scope in which the object is declared. The result is nil for methods and struct fields.

func (*PkgName) Pkg 1.5

func (obj *PkgName) Pkg() *Package

Pkg returns the package to which the object belongs. The result is nil for labels and objects in the Universe scope.

func (*PkgName) Pos 1.5

func (obj *PkgName) Pos() token.Pos

Pos returns the declaration position of the object's identifier.

func (*PkgName) String 1.5

func (obj *PkgName) String() string

func (*PkgName) Type 1.5

func (obj *PkgName) Type() Type

Type returns the object's type.

type Pointer 1.5

A Pointer represents a pointer type.

type Pointer struct {
    // contains filtered or unexported fields
}

func NewPointer 1.5

func NewPointer(elem Type) *Pointer

NewPointer returns a new pointer type for the given element (base) type.

func (*Pointer) Elem 1.5

func (p *Pointer) Elem() Type

Elem returns the element type for the given pointer p.

func (*Pointer) String 1.5

func (p *Pointer) String() string

func (*Pointer) Underlying 1.5

func (p *Pointer) Underlying() Type

type Qualifier 1.5

A Qualifier controls how named package-level objects are printed in calls to TypeString, ObjectString, and SelectionString.

These three formatting routines call the Qualifier for each package-level object O, and if the Qualifier returns a non-empty string p, the object is printed in the form p.O. If it returns an empty string, only the object name O is printed.

Using a nil Qualifier is equivalent to using (*Package).Path: the object is qualified by the import path, e.g., "encoding/json.Marshal".

type Qualifier func(*Package) string

func RelativeTo 1.5

func RelativeTo(pkg *Package) Qualifier

RelativeTo returns a Qualifier that fully qualifies members of all packages other than pkg.

type Scope 1.5

A Scope maintains a set of objects and links to its containing (parent) and contained (children) scopes. Objects may be inserted and looked up by name. The zero value for Scope is a ready-to-use empty scope.

type Scope struct {
    // contains filtered or unexported fields
}

The Universe scope contains all predeclared objects of Go. It is the outermost scope of any chain of nested scopes.

var Universe *Scope

Example

ExampleScope prints the tree of Scopes of a package created from a set of parsed files.

Code:

// Parse the source files for a package.
fset := token.NewFileSet()
var files []*ast.File
for _, src := range []string{
    `package main
import "fmt"
func main() {
    freezing := FToC(-18)
    fmt.Println(freezing, Boiling) }
`,
    `package main
import "fmt"
type Celsius float64
func (c Celsius) String() string { return fmt.Sprintf("%g°C", c) }
func FToC(f float64) Celsius { return Celsius(f - 32 / 9 * 5) }
const Boiling Celsius = 100
func Unused() { {}; {{ var x int; _ = x }} } // make sure empty block scopes get printed
`,
} {
    files = append(files, mustParse(fset, src))
}

// Type-check a package consisting of these files.
// Type information for the imported "fmt" package
// comes from $GOROOT/pkg/$GOOS_$GOOARCH/fmt.a.
conf := types.Config{Importer: importer.Default()}
pkg, err := conf.Check("temperature", fset, files, nil)
if err != nil {
    log.Fatal(err)
}

// Print the tree of scopes.
// For determinism, we redact addresses.
var buf strings.Builder
pkg.Scope().WriteTo(&buf, 0, true)
rx := regexp.MustCompile(` 0x[a-fA-F\d]*`)
fmt.Println(rx.ReplaceAllString(buf.String(), ""))

Output:

package "temperature" scope {
.  const temperature.Boiling temperature.Celsius
.  type temperature.Celsius float64
.  func temperature.FToC(f float64) temperature.Celsius
.  func temperature.Unused()
.  func temperature.main()
.  main scope {
.  .  package fmt
.  .  function scope {
.  .  .  var freezing temperature.Celsius
.  .  }
.  }
.  main scope {
.  .  package fmt
.  .  function scope {
.  .  .  var c temperature.Celsius
.  .  }
.  .  function scope {
.  .  .  var f float64
.  .  }
.  .  function scope {
.  .  .  block scope {
.  .  .  }
.  .  .  block scope {
.  .  .  .  block scope {
.  .  .  .  .  var x int
.  .  .  .  }
.  .  .  }
.  .  }
.  }
}

func NewScope 1.5

func NewScope(parent *Scope, pos, end token.Pos, comment string) *Scope

NewScope returns a new, empty scope contained in the given parent scope, if any. The comment is for debugging only.

func (*Scope) Child 1.5

func (s *Scope) Child(i int) *Scope

Child returns the i'th child scope for 0 <= i < NumChildren().

func (*Scope) Contains 1.5

func (s *Scope) Contains(pos token.Pos) bool

Contains reports whether pos is within the scope's extent. The result is guaranteed to be valid only if the type-checked AST has complete position information.

func (*Scope) End 1.5

func (s *Scope) End() token.Pos

func (*Scope) Innermost 1.5

func (s *Scope) Innermost(pos token.Pos) *Scope

Innermost returns the innermost (child) scope containing pos. If pos is not within any scope, the result is nil. The result is also nil for the Universe scope. The result is guaranteed to be valid only if the type-checked AST has complete position information.

func (*Scope) Insert 1.5

func (s *Scope) Insert(obj Object) Object

Insert attempts to insert an object obj into scope s. If s already contains an alternative object alt with the same name, Insert leaves s unchanged and returns alt. Otherwise it inserts obj, sets the object's parent scope if not already set, and returns nil.

func (*Scope) Len 1.5

func (s *Scope) Len() int

Len returns the number of scope elements.

func (*Scope) Lookup 1.5

func (s *Scope) Lookup(name string) Object

Lookup returns the object in scope s with the given name if such an object exists; otherwise the result is nil.

func (*Scope) LookupParent 1.5

func (s *Scope) LookupParent(name string, pos token.Pos) (*Scope, Object)

LookupParent follows the parent chain of scopes starting with s until it finds a scope where Lookup(name) returns a non-nil object, and then returns that scope and object. If a valid position pos is provided, only objects that were declared at or before pos are considered. If no such scope and object exists, the result is (nil, nil).

Note that obj.Parent() may be different from the returned scope if the object was inserted into the scope and already had a parent at that time (see Insert). This can only happen for dot-imported objects whose scope is the scope of the package that exported them.

func (*Scope) Names 1.5

func (s *Scope) Names() []string

Names returns the scope's element names in sorted order.

func (*Scope) NumChildren 1.5

func (s *Scope) NumChildren() int

NumChildren returns the number of scopes nested in s.

func (*Scope) Parent 1.5

func (s *Scope) Parent() *Scope

Parent returns the scope's containing (parent) scope.

func (*Scope) Pos 1.5

func (s *Scope) Pos() token.Pos

Pos and End describe the scope's source code extent [pos, end). The results are guaranteed to be valid only if the type-checked AST has complete position information. The extent is undefined for Universe and package scopes.

func (*Scope) String 1.5

func (s *Scope) String() string

String returns a string representation of the scope, for debugging.

func (*Scope) WriteTo 1.5

func (s *Scope) WriteTo(w io.Writer, n int, recurse bool)

WriteTo writes a string representation of the scope to w, with the scope elements sorted by name. The level of indentation is controlled by n >= 0, with n == 0 for no indentation. If recurse is set, it also writes nested (children) scopes.

type Selection 1.5

A Selection describes a selector expression x.f. For the declarations:

type T struct{ x int; E }
type E struct{}
func (e E) m() {}
var p *T

the following relations exist:

Selector    Kind          Recv    Obj    Type       Index     Indirect

p.x         FieldVal      T       x      int        {0}       true
p.m         MethodVal     *T      m      func()     {1, 0}    true
T.m         MethodExpr    T       m      func(T)    {1, 0}    false
type Selection struct {
    // contains filtered or unexported fields
}

func (*Selection) Index 1.5

func (s *Selection) Index() []int

Index describes the path from x to f in x.f. The last index entry is the field or method index of the type declaring f; either:

  1. the list of declared methods of a named type; or
  2. the list of methods of an interface type; or
  3. the list of fields of a struct type.

The earlier index entries are the indices of the embedded fields implicitly traversed to get from (the type of) x to f, starting at embedding depth 0.

func (*Selection) Indirect 1.5

func (s *Selection) Indirect() bool

Indirect reports whether any pointer indirection was required to get from x to f in x.f.

Beware: Indirect spuriously returns true (Go issue #8353) for a MethodVal selection in which the receiver argument and parameter both have type *T so there is no indirection. Unfortunately, a fix is too risky.

func (*Selection) Kind 1.5

func (s *Selection) Kind() SelectionKind

Kind returns the selection kind.

func (*Selection) Obj 1.5

func (s *Selection) Obj() Object

Obj returns the object denoted by x.f; a *Var for a field selection, and a *Func in all other cases.

func (*Selection) Recv 1.5

func (s *Selection) Recv() Type

Recv returns the type of x in x.f.

func (*Selection) String 1.5

func (s *Selection) String() string

func (*Selection) Type 1.5

func (s *Selection) Type() Type

Type returns the type of x.f, which may be different from the type of f. See Selection for more information.

type SelectionKind 1.5

SelectionKind describes the kind of a selector expression x.f (excluding qualified identifiers).

If x is a struct or *struct, a selector expression x.f may denote a sequence of selection operations x.a.b.c.f. The SelectionKind describes the kind of the final (explicit) operation; all the previous (implicit) operations are always field selections. Each element of Indices specifies an implicit field (a, b, c) by its index in the struct type of the field selection operand.

For a FieldVal operation, the final selection refers to the field specified by Selection.Obj.

For a MethodVal operation, the final selection refers to a method. If the "pointerness" of the method's declared receiver does not match that of the effective receiver after implicit field selection, then an & or * operation is implicitly applied to the receiver variable or value. So, x.f denotes (&x.a.b.c).f when f requires a pointer receiver but x.a.b.c is a non-pointer variable; and it denotes (*x.a.b.c).f when f requires a non-pointer receiver but x.a.b.c is a pointer value.

All pointer indirections, whether due to implicit or explicit field selections or * operations inserted for "pointerness", panic if applied to a nil pointer, so a method call x.f() may panic even before the function call.

By contrast, a MethodExpr operation T.f is essentially equivalent to a function literal of the form:

func(x T, args) (results) { return x.f(args) }

Consequently, any implicit field selections and * operations inserted for "pointerness" are not evaluated until the function is called, so a T.f or (*T).f expression never panics.

type SelectionKind int
const (
    FieldVal   SelectionKind = iota // x.f is a struct field selector
    MethodVal                       // x.f is a method selector
    MethodExpr                      // x.f is a method expression
)

type Signature 1.5

A Signature represents a (non-builtin) function or method type. The receiver is ignored when comparing signatures for identity.

type Signature struct {
    // contains filtered or unexported fields
}

func NewSignature 1.5

func NewSignature(recv *Var, params, results *Tuple, variadic bool) *Signature

NewSignature returns a new function type for the given receiver, parameters, and results, either of which may be nil. If variadic is set, the function is variadic, it must have at least one parameter, and the last parameter must be of unnamed slice type.

Deprecated: Use NewSignatureType instead which allows for type parameters.

func NewSignatureType 1.18

func NewSignatureType(recv *Var, recvTypeParams, typeParams []*TypeParam, params, results *Tuple, variadic bool) *Signature

NewSignatureType creates a new function type for the given receiver, receiver type parameters, type parameters, parameters, and results. If variadic is set, params must hold at least one parameter and the last parameter's core type must be of unnamed slice or bytestring type. If recv is non-nil, typeParams must be empty. If recvTypeParams is non-empty, recv must be non-nil.

func (*Signature) Params 1.5

func (s *Signature) Params() *Tuple

Params returns the parameters of signature s, or nil.

func (*Signature) Recv 1.5

func (s *Signature) Recv() *Var

Recv returns the receiver of signature s (if a method), or nil if a function. It is ignored when comparing signatures for identity.

For an abstract method, Recv returns the enclosing interface either as a *Named or an *Interface. Due to embedding, an interface may contain methods whose receiver type is a different interface.

func (*Signature) RecvTypeParams 1.18

func (s *Signature) RecvTypeParams() *TypeParamList

RecvTypeParams returns the receiver type parameters of signature s, or nil.

func (*Signature) Results 1.5

func (s *Signature) Results() *Tuple

Results returns the results of signature s, or nil.

func (*Signature) String 1.5

func (t *Signature) String() string

func (*Signature) TypeParams 1.18

func (s *Signature) TypeParams() *TypeParamList

TypeParams returns the type parameters of signature s, or nil.

func (*Signature) Underlying 1.5

func (t *Signature) Underlying() Type

func (*Signature) Variadic 1.5

func (s *Signature) Variadic() bool

Variadic reports whether the signature s is variadic.

type Sizes 1.5

Sizes defines the sizing functions for package unsafe.

type Sizes interface {
    // Alignof returns the alignment of a variable of type T.
    // Alignof must implement the alignment guarantees required by the spec.
    // The result must be >= 1.
    Alignof(T Type) int64

    // Offsetsof returns the offsets of the given struct fields, in bytes.
    // Offsetsof must implement the offset guarantees required by the spec.
    // A negative entry in the result indicates that the struct is too large.
    Offsetsof(fields []*Var) []int64

    // Sizeof returns the size of a variable of type T.
    // Sizeof must implement the size guarantees required by the spec.
    // A negative result indicates that T is too large.
    Sizeof(T Type) int64
}

func SizesFor 1.9

func SizesFor(compiler, arch string) Sizes

SizesFor returns the Sizes used by a compiler for an architecture. The result is nil if a compiler/architecture pair is not known.

Supported architectures for compiler "gc": "386", "amd64", "amd64p32", "arm", "arm64", "loong64", "mips", "mipsle", "mips64", "mips64le", "ppc64", "ppc64le", "riscv64", "s390x", "sparc64", "wasm".

type Slice 1.5

A Slice represents a slice type.

type Slice struct {
    // contains filtered or unexported fields
}

func NewSlice 1.5

func NewSlice(elem Type) *Slice

NewSlice returns a new slice type for the given element type.

func (*Slice) Elem 1.5

func (s *Slice) Elem() Type

Elem returns the element type of slice s.

func (*Slice) String 1.5

func (s *Slice) String() string

func (*Slice) Underlying 1.5

func (s *Slice) Underlying() Type

type StdSizes 1.5

StdSizes is a convenience type for creating commonly used Sizes. It makes the following simplifying assumptions:

*StdSizes implements Sizes.

type StdSizes struct {
    WordSize int64 // word size in bytes - must be >= 4 (32bits)
    MaxAlign int64 // maximum alignment in bytes - must be >= 1
}

func (*StdSizes) Alignof 1.5

func (s *StdSizes) Alignof(T Type) (result int64)

func (*StdSizes) Offsetsof 1.5

func (s *StdSizes) Offsetsof(fields []*Var) []int64

func (*StdSizes) Sizeof 1.5

func (s *StdSizes) Sizeof(T Type) int64

type Struct 1.5

A Struct represents a struct type.

type Struct struct {
    // contains filtered or unexported fields
}

func NewStruct 1.5

func NewStruct(fields []*Var, tags []string) *Struct

NewStruct returns a new struct with the given fields and corresponding field tags. If a field with index i has a tag, tags[i] must be that tag, but len(tags) may be only as long as required to hold the tag with the largest index i. Consequently, if no field has a tag, tags may be nil.

func (*Struct) Field 1.5

func (s *Struct) Field(i int) *Var

Field returns the i'th field for 0 <= i < NumFields().

func (*Struct) NumFields 1.5

func (s *Struct) NumFields() int

NumFields returns the number of fields in the struct (including blank and embedded fields).

func (*Struct) String 1.5

func (t *Struct) String() string

func (*Struct) Tag 1.5

func (s *Struct) Tag(i int) string

Tag returns the i'th field tag for 0 <= i < NumFields().

func (*Struct) Underlying 1.5

func (t *Struct) Underlying() Type

type Term 1.18

A Term represents a term in a Union.

type Term term

func NewTerm 1.18

func NewTerm(tilde bool, typ Type) *Term

NewTerm returns a new union term.

func (*Term) String 1.18

func (t *Term) String() string

func (*Term) Tilde 1.18

func (t *Term) Tilde() bool

func (*Term) Type 1.18

func (t *Term) Type() Type

type Tuple 1.5

A Tuple represents an ordered list of variables; a nil *Tuple is a valid (empty) tuple. Tuples are used as components of signatures and to represent the type of multiple assignments; they are not first class types of Go.

type Tuple struct {
    // contains filtered or unexported fields
}

func NewTuple 1.5

func NewTuple(x ...*Var) *Tuple

NewTuple returns a new tuple for the given variables.

func (*Tuple) At 1.5

func (t *Tuple) At(i int) *Var

At returns the i'th variable of tuple t.

func (*Tuple) Len 1.5

func (t *Tuple) Len() int

Len returns the number variables of tuple t.

func (*Tuple) String 1.5

func (t *Tuple) String() string

func (*Tuple) Underlying 1.5

func (t *Tuple) Underlying() Type

type Type 1.5

A Type represents a type of Go. All types implement the Type interface.

type Type interface {
    // Underlying returns the underlying type of a type.
    // Underlying types are never Named, TypeParam, or Alias types.
    //
    // See https://go.dev/ref/spec#Underlying_types.
    Underlying() Type

    // String returns a string representation of a type.
    String() string
}

func Default 1.8

func Default(t Type) Type

Default returns the default "typed" type for an "untyped" type; it returns the incoming type for all other types. The default type for untyped nil is untyped nil.

func Instantiate 1.18

func Instantiate(ctxt *Context, orig Type, targs []Type, validate bool) (Type, error)

Instantiate instantiates the type orig with the given type arguments targs. orig must be an *Alias, *Named, or *Signature type. If there is no error, the resulting Type is an instantiated type of the same kind (*Alias, *Named or *Signature, respectively).

Methods attached to a *Named type are also instantiated, and associated with a new *Func that has the same position as the original method, but nil function scope.

If ctxt is non-nil, it may be used to de-duplicate the instance against previous instances with the same identity. As a special case, generic *Signature origin types are only considered identical if they are pointer equivalent, so that instantiating distinct (but possibly identical) signatures will yield different instances. The use of a shared context does not guarantee that identical instances are deduplicated in all cases.

If validate is set, Instantiate verifies that the number of type arguments and parameters match, and that the type arguments satisfy their respective type constraints. If verification fails, the resulting error may wrap an *ArgumentError indicating which type argument did not satisfy its type parameter constraint, and why.

If validate is not set, Instantiate does not verify the type argument count or whether the type arguments satisfy their constraints. Instantiate is guaranteed to not return an error, but may panic. Specifically, for *Signature types, Instantiate will panic immediately if the type argument count is incorrect; for *Named types, a panic may occur later inside the *Named API.

func Unalias 1.22

func Unalias(t Type) Type

Unalias returns t if it is not an alias type; otherwise it follows t's alias chain until it reaches a non-alias type which is then returned. Consequently, the result is never an alias type.

type TypeAndValue 1.5

TypeAndValue reports the type and value (for constants) of the corresponding expression.

type TypeAndValue struct {
    Type  Type
    Value constant.Value
    // contains filtered or unexported fields
}

func Eval 1.5

func Eval(fset *token.FileSet, pkg *Package, pos token.Pos, expr string) (_ TypeAndValue, err error)

Eval returns the type and, if constant, the value for the expression expr, evaluated at position pos of package pkg, which must have been derived from type-checking an AST with complete position information relative to the provided file set.

The meaning of the parameters fset, pkg, and pos is the same as in CheckExpr. An error is returned if expr cannot be parsed successfully, or the resulting expr AST cannot be type-checked.

func (TypeAndValue) Addressable 1.5

func (tv TypeAndValue) Addressable() bool

Addressable reports whether the corresponding expression is addressable (https://golang.org/ref/spec#Address_operators).

func (TypeAndValue) Assignable 1.5

func (tv TypeAndValue) Assignable() bool

Assignable reports whether the corresponding expression is assignable to (provided a value of the right type).

func (TypeAndValue) HasOk 1.5

func (tv TypeAndValue) HasOk() bool

HasOk reports whether the corresponding expression may be used on the rhs of a comma-ok assignment.

func (TypeAndValue) IsBuiltin 1.5

func (tv TypeAndValue) IsBuiltin() bool

IsBuiltin reports whether the corresponding expression denotes a (possibly parenthesized) built-in function.

func (TypeAndValue) IsNil 1.5

func (tv TypeAndValue) IsNil() bool

IsNil reports whether the corresponding expression denotes the predeclared value nil.

func (TypeAndValue) IsType 1.5

func (tv TypeAndValue) IsType() bool

IsType reports whether the corresponding expression specifies a type.

func (TypeAndValue) IsValue 1.5

func (tv TypeAndValue) IsValue() bool

IsValue reports whether the corresponding expression is a value. Builtins are not considered values. Constant values have a non- nil Value.

func (TypeAndValue) IsVoid 1.5

func (tv TypeAndValue) IsVoid() bool

IsVoid reports whether the corresponding expression is a function call without results.

type TypeList 1.18

TypeList holds a list of types.

type TypeList struct {
    // contains filtered or unexported fields
}

func (*TypeList) At 1.18

func (l *TypeList) At(i int) Type

At returns the i'th type in the list.

func (*TypeList) Len 1.18

func (l *TypeList) Len() int

Len returns the number of types in the list. It is safe to call on a nil receiver.

type TypeName 1.5

A TypeName represents a name for a (defined or alias) type.

type TypeName struct {
    // contains filtered or unexported fields
}

func NewTypeName 1.5

func NewTypeName(pos token.Pos, pkg *Package, name string, typ Type) *TypeName

NewTypeName returns a new type name denoting the given typ. The remaining arguments set the attributes found with all Objects.

The typ argument may be a defined (Named) type or an alias type. It may also be nil such that the returned TypeName can be used as argument for NewNamed, which will set the TypeName's type as a side- effect.

func (*TypeName) Exported 1.5

func (obj *TypeName) Exported() bool

Exported reports whether the object is exported (starts with a capital letter). It doesn't take into account whether the object is in a local (function) scope or not.

func (*TypeName) Id 1.5

func (obj *TypeName) Id() string

Id is a wrapper for Id(obj.Pkg(), obj.Name()).

func (*TypeName) IsAlias 1.9

func (obj *TypeName) IsAlias() bool

IsAlias reports whether obj is an alias name for a type.

func (*TypeName) Name 1.5

func (obj *TypeName) Name() string

Name returns the object's (package-local, unqualified) name.

func (*TypeName) Parent 1.5

func (obj *TypeName) Parent() *Scope

Parent returns the scope in which the object is declared. The result is nil for methods and struct fields.

func (*TypeName) Pkg 1.5

func (obj *TypeName) Pkg() *Package

Pkg returns the package to which the object belongs. The result is nil for labels and objects in the Universe scope.

func (*TypeName) Pos 1.5

func (obj *TypeName) Pos() token.Pos

Pos returns the declaration position of the object's identifier.

func (*TypeName) String 1.5

func (obj *TypeName) String() string

func (*TypeName) Type 1.5

func (obj *TypeName) Type() Type

Type returns the object's type.

type TypeParam 1.18

A TypeParam represents a type parameter type.

type TypeParam struct {
    // contains filtered or unexported fields
}

func NewTypeParam 1.18

func NewTypeParam(obj *TypeName, constraint Type) *TypeParam

NewTypeParam returns a new TypeParam. Type parameters may be set on a Named type by calling SetTypeParams. Setting a type parameter on more than one type will result in a panic.

The constraint argument can be nil, and set later via SetConstraint. If the constraint is non-nil, it must be fully defined.

func (*TypeParam) Constraint 1.18

func (t *TypeParam) Constraint() Type

Constraint returns the type constraint specified for t.

func (*TypeParam) Index 1.18

func (t *TypeParam) Index() int

Index returns the index of the type param within its param list, or -1 if the type parameter has not yet been bound to a type.

func (*TypeParam) Obj 1.18

func (t *TypeParam) Obj() *TypeName

Obj returns the type name for the type parameter t.

func (*TypeParam) SetConstraint 1.18

func (t *TypeParam) SetConstraint(bound Type)

SetConstraint sets the type constraint for t.

It must be called by users of NewTypeParam after the bound's underlying is fully defined, and before using the type parameter in any way other than to form other types. Once SetConstraint returns the receiver, t is safe for concurrent use.

func (*TypeParam) String 1.18

func (t *TypeParam) String() string

func (*TypeParam) Underlying 1.18

func (t *TypeParam) Underlying() Type

Underlying returns the underlying type of the type parameter t, which is the underlying type of its constraint. This type is always an interface.

type TypeParamList 1.18

TypeParamList holds a list of type parameters.

type TypeParamList struct {
    // contains filtered or unexported fields
}

func (*TypeParamList) At 1.18

func (l *TypeParamList) At(i int) *TypeParam

At returns the i'th type parameter in the list.

func (*TypeParamList) Len 1.18

func (l *TypeParamList) Len() int

Len returns the number of type parameters in the list. It is safe to call on a nil receiver.

type Union 1.18

A Union represents a union of terms embedded in an interface.

type Union struct {
    // contains filtered or unexported fields
}

func NewUnion 1.18

func NewUnion(terms []*Term) *Union

NewUnion returns a new Union type with the given terms. It is an error to create an empty union; they are syntactically not possible.

func (*Union) Len 1.18

func (u *Union) Len() int

func (*Union) String 1.18

func (u *Union) String() string

func (*Union) Term 1.18

func (u *Union) Term(i int) *Term

func (*Union) Underlying 1.18

func (u *Union) Underlying() Type

type Var 1.5

A Variable represents a declared variable (including function parameters and results, and struct fields).

type Var struct {
    // contains filtered or unexported fields
}

func NewField 1.5

func NewField(pos token.Pos, pkg *Package, name string, typ Type, embedded bool) *Var

NewField returns a new variable representing a struct field. For embedded fields, the name is the unqualified type name under which the field is accessible.

func NewParam 1.5

func NewParam(pos token.Pos, pkg *Package, name string, typ Type) *Var

NewParam returns a new variable representing a function parameter.

func NewVar 1.5

func NewVar(pos token.Pos, pkg *Package, name string, typ Type) *Var

NewVar returns a new variable. The arguments set the attributes found with all Objects.

func (*Var) Anonymous 1.5

func (obj *Var) Anonymous() bool

Anonymous reports whether the variable is an embedded field. Same as Embedded; only present for backward-compatibility.

func (*Var) Embedded 1.11

func (obj *Var) Embedded() bool

Embedded reports whether the variable is an embedded field.

func (*Var) Exported 1.5

func (obj *Var) Exported() bool

Exported reports whether the object is exported (starts with a capital letter). It doesn't take into account whether the object is in a local (function) scope or not.

func (*Var) Id 1.5

func (obj *Var) Id() string

Id is a wrapper for Id(obj.Pkg(), obj.Name()).

func (*Var) IsField 1.5

func (obj *Var) IsField() bool

IsField reports whether the variable is a struct field.

func (*Var) Name 1.5

func (obj *Var) Name() string

Name returns the object's (package-local, unqualified) name.

func (*Var) Origin 1.19

func (obj *Var) Origin() *Var

Origin returns the canonical Var for its receiver, i.e. the Var object recorded in Info.Defs.

For synthetic Vars created during instantiation (such as struct fields or function parameters that depend on type arguments), this will be the corresponding Var on the generic (uninstantiated) type. For all other Vars Origin returns the receiver.

func (*Var) Parent 1.5

func (obj *Var) Parent() *Scope

Parent returns the scope in which the object is declared. The result is nil for methods and struct fields.

func (*Var) Pkg 1.5

func (obj *Var) Pkg() *Package

Pkg returns the package to which the object belongs. The result is nil for labels and objects in the Universe scope.

func (*Var) Pos 1.5

func (obj *Var) Pos() token.Pos

Pos returns the declaration position of the object's identifier.

func (*Var) String 1.5

func (obj *Var) String() string

func (*Var) Type 1.5

func (obj *Var) Type() Type

Type returns the object's type.