Code Examples
{
// 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)
}`
fset := token.NewFileSet()
f := mustParse(fset, input)
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)
}
fmt.Printf("InitOrder: %v\n\n", info.InitOrder)
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)
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()
}
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"))
}
package main
import (
"fmt"
"go/ast"
"go/importer"
"go/parser"
"go/token"
"go/types"
"log"
)
func main() {
// Parse a single source file.
const input = `
package temperature
import "fmt"
type Celsius float64
func (c Celsius) String() string { return fmt.Sprintf("%g°C", c) }
func (c *Celsius) SetF(f float64) { *c = Celsius(f - 32 / 9 * 5) }
type S struct { I; m int }
type I interface { m() byte }
`
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "celsius.go", input, 0)
if err != nil {
log.Fatal(err)
}
// Type-check a package consisting of this file.
// Type information for the imported packages
// comes from $GOROOT/pkg/$GOOS_$GOOARCH/fmt.a.
conf := types.Config{Importer: importer.Default()}
pkg, err := conf.Check("temperature", fset, []*ast.File{f}, nil)
if err != nil {
log.Fatal(err)
}
// Print the method sets of Celsius and *Celsius.
celsius := pkg.Scope().Lookup("Celsius").Type()
for _, t := range []types.Type{celsius, types.NewPointer(celsius)} {
fmt.Printf("Method set of %s:\n", t)
mset := types.NewMethodSet(t)
for i := 0; i < mset.Len(); i++ {
fmt.Println(mset.At(i))
}
fmt.Println()
}
// Print the method set of S.
styp := pkg.Scope().Lookup("S").Type()
fmt.Printf("Method set of %s:\n", styp)
fmt.Println(types.NewMethodSet(styp))
}
{
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))
}
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(), ""))
}
Package-Level Type Names (total 50)
/* sort by: | */
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. 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. 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. Rhs returns the type R on the right-hand side of an alias
declaration "type A = R", which may be another alias. SetTypeParams sets the type parameters of the alias type a.
The alias a must not have type arguments.(*Alias) String() string 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. TypeParams returns the type parameters of the alias type a, or nil.
A generic Alias and its instances have the same type parameters. 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.
*Alias : Type
*Alias : expvar.Var
*Alias : fmt.Stringer
func NewAlias(obj *TypeName, rhs Type) *Alias
func (*Alias).Origin() *Alias
An Array represents an array type.
Elem returns element type of array a.
Len returns the length of array a.
A negative result indicates an unknown length.(*Array) String() string(*Array) Underlying() Type
*Array : Type
*Array : expvar.Var
*Array : fmt.Stringer
func NewArray(elem Type, len int64) *Array
A Basic represents a basic type. Info returns information about properties of basic type b. Kind returns the kind of basic type b. Name returns the name of basic type b.(*Basic) String() string(*Basic) Underlying() Type
*Basic : Type
*Basic : expvar.Var
*Basic : fmt.Stringer
A Builtin represents a built-in function.
Builtins don't have a valid type. 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. Id is a wrapper for Id(obj.Pkg(), obj.Name()). Name returns the object's (package-local, unqualified) name. Parent returns the scope in which the object is declared.
The result is nil for methods and struct fields. Pkg returns the package to which the object belongs.
The result is nil for labels and objects in the Universe scope. Pos returns the declaration position of the object's identifier.(*Builtin) String() string Type returns the object's type.
*Builtin : Object
*Builtin : expvar.Var
*Builtin : fmt.Stringer
A Chan represents a channel type. Dir returns the direction of channel c. Elem returns the element type of channel c.(*Chan) String() string(*Chan) Underlying() Type
*Chan : Type
*Chan : expvar.Var
*Chan : fmt.Stringer
func NewChan(dir ChanDir, elem Type) *Chan
A Checker maintains the state of the type checker.
It must be created with [NewChecker].Info*Info 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() 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. 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) 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. 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. 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 Selections maps selector expressions (excluding qualified identifiers)
to their corresponding selections. 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. Uses maps identifiers to the objects they denote.
For an embedded field, Uses returns the *TypeName it denotes.
Invariant: Uses[id].Pos() != id.Pos() Files checks the provided files as part of the checker's package. 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. 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. TypeOf returns the type of expression e, or nil if not found.
Precondition: the Types, Uses and Defs maps are populated.
func NewChecker(conf *Config, fset *token.FileSet, pkg *Package, info *Info) *Checker
A Config specifies the configuration for type checking.
The zero value for Config is a ready-to-use default configuration. Context is the context used for resolving global identifiers. If nil, the
type checker will initialize this field with a newly created context. If DisableUnusedImportCheck is set, packages are not checked
for unused imports. 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. 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! 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. If IgnoreFuncBodies is set, function bodies are not
type-checked. 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. If Sizes != nil, it provides the sizing functions for package unsafe.
Otherwise SizesFor("gc", "amd64") is used instead. 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 (".").
func NewChecker(conf *Config, fset *token.FileSet, pkg *Package, info *Info) *Checker
A Const represents a declared constant. 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. Id is a wrapper for Id(obj.Pkg(), obj.Name()). Name returns the object's (package-local, unqualified) name. Parent returns the scope in which the object is declared.
The result is nil for methods and struct fields. Pkg returns the package to which the object belongs.
The result is nil for labels and objects in the Universe scope. Pos returns the declaration position of the object's identifier.(*Const) String() string Type returns the object's type. Val returns the constant's value.
*Const : Object
*Const : expvar.Var
*Const : fmt.Stringer
func NewConst(pos token.Pos, pkg *Package, name string, typ Type, val constant.Value) *Const
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.
func NewContext() *Context
func Instantiate(ctxt *Context, orig Type, targs []Type, validate bool) (Type, error)
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. // file set for interpretation of Pos // error message // error position // if set, error is "soft" Error returns an error string formatted as follows:
filename:line:column: message
Error : error
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. 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. FullName returns the package- or receiver-type-qualified name of
function or method obj. Id is a wrapper for Id(obj.Pkg(), obj.Name()). Name returns the object's (package-local, unqualified) name. 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. Parent returns the scope in which the object is declared.
The result is nil for methods and struct fields. 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. Pos returns the declaration position of the object's identifier. 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). Signature returns the signature (type) of the function or method.(*Func) String() string Type returns the object's type.
*Func : Object
*Func : expvar.Var
*Func : fmt.Stringer
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 (*Func).Origin() *Func
func (*Interface).ExplicitMethod(i int) *Func
func (*Interface).Method(i int) *Func
func (*Named).Method(i int) *Func
func NewInterface(methods []*Func, embeddeds []*Named) *Interface
func NewInterfaceType(methods []*Func, embeddeds []Type) *Interface
func NewNamed(obj *TypeName, underlying Type, methods []*Func) *Named
func (*Named).AddMethod(m *Func)
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]. 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).ImporterFrom(interface)
*go/internal/srcimporter.Importer
func go/importer.Default() Importer
func go/importer.For(compiler string, lookup importer.Lookup) Importer
func go/importer.ForCompiler(fset *token.FileSet, compiler string, lookup importer.Lookup) Importer
An ImporterFrom resolves import paths to packages; it
supports vendoring per https://golang.org/s/go15vendor.
Use go/importer to obtain an ImporterFrom implementation. 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). 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.
*go/internal/srcimporter.Importer
ImporterFrom : Importer
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. 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() 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. 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) 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. 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. 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 Selections maps selector expressions (excluding qualified identifiers)
to their corresponding selections. 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. Uses maps identifiers to the objects they denote.
For an embedded field, Uses returns the *TypeName it denotes.
Invariant: Uses[id].Pos() != id.Pos() 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. 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. TypeOf returns the type of expression e, or nil if not found.
Precondition: the Types, Uses and Defs maps are populated.
func CheckExpr(fset *token.FileSet, pkg *Package, pos token.Pos, expr ast.Expr, info *Info) (err error)
func NewChecker(conf *Config, fset *token.FileSet, pkg *Package, info *Info) *Checker
func (*Config).Check(path string, fset *token.FileSet, files []*ast.File, info *Info) (*Package, error)
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. // var Lhs = RhsRhsast.Expr(*Initializer) String() string
*Initializer : expvar.Var
*Initializer : fmt.Stringer
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.TypeTypeTypeArgs*TypeList
An Interface represents an interface type. 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. 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. EmbeddedType returns the i'th embedded type of interface t for 0 <= i < t.NumEmbeddeds(). Empty reports whether t is the empty interface. ExplicitMethod returns the i'th explicitly declared method of interface t for 0 <= i < t.NumExplicitMethods().
The methods are ordered by their unique [Id]. IsComparable reports whether each type in interface t's type set is comparable. IsImplicit reports whether the interface t is a wrapper for a type set literal. IsMethodSet reports whether the interface t is fully described by its method
set. 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. Method returns the i'th method of interface t for 0 <= i < t.NumMethods().
The methods are ordered by their unique Id. NumEmbeddeds returns the number of embedded types in interface t. NumExplicitMethods returns the number of explicitly declared methods of interface t. NumMethods returns the total number of methods of interface t.(*Interface) String() string(*Interface) Underlying() Type
*Interface : Type
*Interface : expvar.Var
*Interface : fmt.Stringer
func NewInterface(methods []*Func, embeddeds []*Named) *Interface
func NewInterfaceType(methods []*Func, embeddeds []Type) *Interface
func (*Interface).Complete() *Interface
func AssertableTo(V *Interface, T Type) bool
func Implements(V Type, T *Interface) bool
func MissingMethod(V Type, T *Interface, static bool) (method *Func, wrongType bool)
func Satisfies(V Type, T *Interface) bool
A Label represents a declared label.
Labels don't have a type. 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. Id is a wrapper for Id(obj.Pkg(), obj.Name()). Name returns the object's (package-local, unqualified) name. Parent returns the scope in which the object is declared.
The result is nil for methods and struct fields. Pkg returns the package to which the object belongs.
The result is nil for labels and objects in the Universe scope. Pos returns the declaration position of the object's identifier.(*Label) String() string Type returns the object's type.
*Label : Object
*Label : expvar.Var
*Label : fmt.Stringer
func NewLabel(pos token.Pos, pkg *Package, name string) *Label
A Map represents a map type. Elem returns the element type of map m. Key returns the key type of map m.(*Map) String() string(*Map) Underlying() Type
*Map : Type
*Map : expvar.Var
*Map : fmt.Stringer
func NewMap(key, elem Type) *Map
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. At returns the i'th method in s for 0 <= i < s.Len(). Len returns the number of methods in s. Lookup returns the method with matching package and name, or nil if not found.(*MethodSet) String() string
*MethodSet : expvar.Var
*MethodSet : fmt.Stringer
func NewMethodSet(T Type) *MethodSet
A Named represents a named (defined) type. 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. 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. NumMethods returns the number of explicit methods defined for t. 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. Origin returns the generic type from which the named type t is
instantiated. If t is not an instantiated type, the result is t. SetTypeParams sets the type parameters of the named type t.
t must not have type arguments. SetUnderlying sets the underlying type and marks t as complete.
t must not have type arguments.(*Named) String() string TypeArgs returns the type arguments used to instantiate the named type t. 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. Underlying returns the [underlying type] of the named type t, resolving all
forwarding declarations. Underlying types are never Named, TypeParam, or
Alias types.
*Named : Type
*Named : expvar.Var
*Named : fmt.Stringer
func NewNamed(obj *TypeName, underlying Type, methods []*Func) *Named
func (*Interface).Embedded(i int) *Named
func (*Named).Origin() *Named
func NewInterface(methods []*Func, embeddeds []*Named) *Interface
Nil represents the predeclared value nil.
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. Id is a wrapper for Id(obj.Pkg(), obj.Name()). Name returns the object's (package-local, unqualified) name. Parent returns the scope in which the object is declared.
The result is nil for methods and struct fields. Pkg returns the package to which the object belongs.
The result is nil for labels and objects in the Universe scope. Pos returns the declaration position of the object's identifier.(*Nil) String() string Type returns the object's type.
*Nil : Object
*Nil : expvar.Var
*Nil : fmt.Stringer
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. // reports whether the name starts with a capital letter // object name if exported, qualified name if not exported (see func Id) // package local object name // scope in which this object is declared; nil for methods and struct fields // package to which this object belongs; nil for labels and objects in the Universe scope // position of object identifier in declaration String returns a human-readable string of the object. // object type
*Builtin
*Const
*Func
*Label
*Nil
*PkgName
*TypeName
*Var
Object : expvar.Var
Object : fmt.Stringer
func LookupFieldOrMethod(T Type, addressable bool, pkg *Package, name string) (obj Object, index []int, indirect bool)
func (*Info).ObjectOf(id *ast.Ident) Object
func (*Scope).Insert(obj Object) Object
func (*Scope).Lookup(name string) Object
func (*Scope).LookupParent(name string, pos token.Pos) (*Scope, Object)
func (*Selection).Obj() Object
func ObjectString(obj Object, qf Qualifier) string
func (*Scope).Insert(obj Object) Object
A PkgName represents an imported Go package.
PkgNames don't have a type. 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. Id is a wrapper for Id(obj.Pkg(), obj.Name()). Imported returns the package that was imported.
It is distinct from Pkg(), which is the package containing the import statement. Name returns the object's (package-local, unqualified) name. Parent returns the scope in which the object is declared.
The result is nil for methods and struct fields. Pkg returns the package to which the object belongs.
The result is nil for labels and objects in the Universe scope. Pos returns the declaration position of the object's identifier.(*PkgName) String() string Type returns the object's type.
*PkgName : Object
*PkgName : expvar.Var
*PkgName : fmt.Stringer
func NewPkgName(pos token.Pos, pkg *Package, name string, imported *Package) *PkgName
func (*Info).PkgNameOf(imp *ast.ImportSpec) *PkgName
A Pointer represents a pointer type. Elem returns the element type for the given pointer p.(*Pointer) String() string(*Pointer) Underlying() Type
*Pointer : Type
*Pointer : expvar.Var
*Pointer : fmt.Stringer
func NewPointer(elem Type) *Pointer
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".
func RelativeTo(pkg *Package) Qualifier
func ObjectString(obj Object, qf Qualifier) string
func SelectionString(s *Selection, qf Qualifier) string
func TypeString(typ Type, qf Qualifier) string
func WriteSignature(buf *bytes.Buffer, sig *Signature, qf Qualifier)
func WriteType(buf *bytes.Buffer, typ Type, qf Qualifier)
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. Child returns the i'th child scope for 0 <= i < NumChildren(). 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.(*Scope) End() token.Pos 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. 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. Len returns the number of scope elements. Lookup returns the object in scope s with the given name if such an
object exists; otherwise the result is nil. 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. Names returns the scope's element names in sorted order. NumChildren returns the number of scopes nested in s. Parent returns the scope's containing (parent) scope. 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. String returns a string representation of the scope, for debugging. 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.
*Scope : go/ast.Node
*Scope : expvar.Var
*Scope : fmt.Stringer
func NewScope(parent *Scope, pos, end token.Pos, comment string) *Scope
func (*Func).Scope() *Scope
func Object.Parent() *Scope
func (*Package).Scope() *Scope
func (*Scope).Child(i int) *Scope
func (*Scope).Innermost(pos token.Pos) *Scope
func (*Scope).LookupParent(name string, pos token.Pos) (*Scope, Object)
func (*Scope).Parent() *Scope
func NewScope(parent *Scope, pos, end token.Pos, comment string) *Scope
var Universe *Scope
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 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. 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. Kind returns the selection kind. Obj returns the object denoted by x.f; a *Var for
a field selection, and a *Func in all other cases. Recv returns the type of x in x.f.(*Selection) String() string Type returns the type of x.f, which may be different from the type of f.
See Selection for more information.
*Selection : expvar.Var
*Selection : fmt.Stringer
func (*MethodSet).At(i int) *Selection
func (*MethodSet).Lookup(pkg *Package, name string) *Selection
func SelectionString(s *Selection, qf Qualifier) string
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.
func (*Selection).Kind() SelectionKind
const FieldVal
const MethodExpr
const MethodVal
A Signature represents a (non-builtin) function or method type.
The receiver is ignored when comparing signatures for identity. Params returns the parameters of signature s, or nil. 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. RecvTypeParams returns the receiver type parameters of signature s, or nil. Results returns the results of signature s, or nil.(*Signature) String() string TypeParams returns the type parameters of signature s, or nil.(*Signature) Underlying() Type Variadic reports whether the signature s is variadic.
*Signature : Type
*Signature : expvar.Var
*Signature : fmt.Stringer
func NewSignature(recv *Var, params, results *Tuple, variadic bool) *Signature
func NewSignatureType(recv *Var, recvTypeParams, typeParams []*TypeParam, params, results *Tuple, variadic bool) *Signature
func (*Func).Signature() *Signature
func NewFunc(pos token.Pos, pkg *Package, name string, sig *Signature) *Func
func WriteSignature(buf *bytes.Buffer, sig *Signature, qf Qualifier)
Sizes defines the sizing functions for package unsafe. 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. 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. 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.
*StdSizes
func SizesFor(compiler, arch string) Sizes
A Slice represents a slice type. Elem returns the element type of slice s.(*Slice) String() string(*Slice) Underlying() Type
*Slice : Type
*Slice : expvar.Var
*Slice : fmt.Stringer
func NewSlice(elem Type) *Slice
StdSizes is a convenience type for creating commonly used Sizes.
It makes the following simplifying assumptions:
- The size of explicitly sized basic types (int16, etc.) is the
specified size.
- The size of strings and interfaces is 2*WordSize.
- The size of slices is 3*WordSize.
- The size of an array of n elements corresponds to the size of
a struct of n consecutive fields of the array's element type.
- The size of a struct is the offset of the last field plus that
field's size. As with all element types, if the struct is used
in an array its size must first be aligned to a multiple of the
struct's alignment.
- All other types have size WordSize.
- Arrays and structs are aligned per spec definition; all other
types are naturally aligned with a maximum alignment MaxAlign.
*StdSizes implements Sizes. // maximum alignment in bytes - must be >= 1 // word size in bytes - must be >= 4 (32bits)(*StdSizes) Alignof(T Type) (result int64)(*StdSizes) Offsetsof(fields []*Var) []int64(*StdSizes) Sizeof(T Type) int64
*StdSizes : Sizes
A Struct represents a struct type. Field returns the i'th field for 0 <= i < NumFields(). NumFields returns the number of fields in the struct (including blank and embedded fields).(*Struct) String() string Tag returns the i'th field tag for 0 <= i < NumFields().(*Struct) Underlying() Type
*Struct : Type
*Struct : expvar.Var
*Struct : fmt.Stringer
func NewStruct(fields []*Var, tags []string) *Struct
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. At returns the i'th variable of tuple t. Len returns the number variables of tuple t.(*Tuple) String() string(*Tuple) Underlying() Type
*Tuple : Type
*Tuple : expvar.Var
*Tuple : fmt.Stringer
func NewTuple(x ...*Var) *Tuple
func (*Signature).Params() *Tuple
func (*Signature).Results() *Tuple
func NewSignature(recv *Var, params, results *Tuple, variadic bool) *Signature
func NewSignatureType(recv *Var, recvTypeParams, typeParams []*TypeParam, params, results *Tuple, variadic bool) *Signature
TypeAndValue reports the type and value (for constants)
of the corresponding expression.TypeTypeValueconstant.Value Addressable reports whether the corresponding expression
is addressable (https://golang.org/ref/spec#Address_operators). Assignable reports whether the corresponding expression
is assignable to (provided a value of the right type). HasOk reports whether the corresponding expression may be
used on the rhs of a comma-ok assignment. IsBuiltin reports whether the corresponding expression denotes
a (possibly parenthesized) built-in function. IsNil reports whether the corresponding expression denotes the
predeclared value nil. IsType reports whether the corresponding expression specifies a type. IsValue reports whether the corresponding expression is a value.
Builtins are not considered values. Constant values have a non-
nil Value. IsVoid reports whether the corresponding expression
is a function call without results.
func Eval(fset *token.FileSet, pkg *Package, pos token.Pos, expr string) (_ TypeAndValue, err error)
TypeList holds a list of types. At returns the i'th type in the list. Len returns the number of types in the list.
It is safe to call on a nil receiver.
func (*Alias).TypeArgs() *TypeList
func (*Named).TypeArgs() *TypeList
A TypeName represents a name for a (defined or alias) type. 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. Id is a wrapper for Id(obj.Pkg(), obj.Name()). IsAlias reports whether obj is an alias name for a type. Name returns the object's (package-local, unqualified) name. Parent returns the scope in which the object is declared.
The result is nil for methods and struct fields. Pkg returns the package to which the object belongs.
The result is nil for labels and objects in the Universe scope. Pos returns the declaration position of the object's identifier.(*TypeName) String() string Type returns the object's type.
*TypeName : Object
*TypeName : expvar.Var
*TypeName : fmt.Stringer
func NewTypeName(pos token.Pos, pkg *Package, name string, typ Type) *TypeName
func (*Alias).Obj() *TypeName
func (*Named).Obj() *TypeName
func (*TypeParam).Obj() *TypeName
func NewAlias(obj *TypeName, rhs Type) *Alias
func NewNamed(obj *TypeName, underlying Type, methods []*Func) *Named
func NewTypeParam(obj *TypeName, constraint Type) *TypeParam
A TypeParam represents a type parameter type. Constraint returns the type constraint specified for t. 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. Obj returns the type name for the type parameter t. 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.(*TypeParam) String() string Underlying returns the [underlying type] of the type parameter t, which is
the underlying type of its constraint. This type is always an interface.
*TypeParam : Type
*TypeParam : expvar.Var
*TypeParam : fmt.Stringer
func NewTypeParam(obj *TypeName, constraint Type) *TypeParam
func (*TypeParamList).At(i int) *TypeParam
func NewSignatureType(recv *Var, recvTypeParams, typeParams []*TypeParam, params, results *Tuple, variadic bool) *Signature
func (*Alias).SetTypeParams(tparams []*TypeParam)
func (*Named).SetTypeParams(tparams []*TypeParam)
TypeParamList holds a list of type parameters.
At returns the i'th type parameter in the list.
Len returns the number of type parameters in the list.
It is safe to call on a nil receiver.
func (*Alias).TypeParams() *TypeParamList
func (*Named).TypeParams() *TypeParamList
func (*Signature).RecvTypeParams() *TypeParamList
func (*Signature).TypeParams() *TypeParamList
A Variable represents a declared variable (including function parameters and results, and struct fields). Anonymous reports whether the variable is an embedded field.
Same as Embedded; only present for backward-compatibility. Embedded reports whether the variable is an embedded field. 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. Id is a wrapper for Id(obj.Pkg(), obj.Name()). IsField reports whether the variable is a struct field. Name returns the object's (package-local, unqualified) name. 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. Parent returns the scope in which the object is declared.
The result is nil for methods and struct fields. Pkg returns the package to which the object belongs.
The result is nil for labels and objects in the Universe scope. Pos returns the declaration position of the object's identifier.(*Var) String() string Type returns the object's type.
*Var : Object
*Var : expvar.Var
*Var : fmt.Stringer
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 (*Signature).Recv() *Var
func (*Struct).Field(i int) *Var
func (*Tuple).At(i int) *Var
func (*Var).Origin() *Var
func NewSignature(recv *Var, params, results *Tuple, variadic bool) *Signature
func NewSignatureType(recv *Var, recvTypeParams, typeParams []*TypeParam, params, results *Tuple, variadic bool) *Signature
func NewStruct(fields []*Var, tags []string) *Struct
func NewTuple(x ...*Var) *Tuple
func Sizes.Offsetsof(fields []*Var) []int64
func (*StdSizes).Offsetsof(fields []*Var) []int64
Package-Level Functions (total 56)
AssertableTo reports whether a value of type V can be asserted to have type T.
The behavior of AssertableTo is unspecified in three cases:
- if T is Typ[Invalid]
- if V is a generalized interface; i.e., an interface that may only be used
as a type constraint in Go code
- if T is an uninstantiated generic type
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.
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.
Comparable reports whether values of type T are comparable.
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.
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.
DefPredeclaredTestFuncs defines the assert and trace built-ins.
These built-ins are intended for debugging and testing of this
package only.
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.
ExprString returns the (possibly shortened) string representation for x.
Shortened representations are suitable for user interfaces but may not
necessarily follow Go syntax.
Id returns name if it is exported, otherwise it
returns the name qualified with the package path.
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.
IdenticalIgnoreTags reports whether x and y are identical types if tags are ignored.
Receivers of [Signature] types are ignored.
Implements reports whether type V implements interface T.
The behavior of Implements is unspecified if V is Typ[Invalid] or an uninstantiated
generic type.
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.
IsInterface reports whether t is an interface type.
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:
- If index != nil, the index sequence points to an ambiguous entry
(the same name appeared more than once at the same embedding level).
- If indirect is set, a method with a pointer receiver type was found
but there was no pointer on the path from the actual receiver type to
the method's formal receiver base type, nor was the receiver addressable.
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).
NewAlias creates a new Alias type with the given type name and rhs.
rhs must not be nil.
NewArray returns a new array type for the given element type and length.
A negative length indicates an unknown length.
NewChan returns a new channel type for the given direction and element type.
NewChecker returns a new [Checker] instance for a given package.
[Package] files may be added incrementally via checker.Files.
NewConst returns a new constant with value val.
The remaining arguments set the attributes found with all Objects.
NewContext creates a new Context.
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.
NewFunc returns a new function with the given signature, representing
the function's type.
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.
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.
NewLabel returns a new label.
NewMap returns a new map for the given key and element types.
NewMethodSet returns the method set for the given type T.
It always returns a non-nil method set, even if it is empty.
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.
NewPackage returns a new Package for the given package path and name.
The package is not complete and contains no explicit imports.
NewParam returns a new variable representing a function parameter.
NewPkgName returns a new PkgName object representing an imported package.
The remaining arguments set the attributes found with all Objects.
NewPointer returns a new pointer type for the given element (base) type.
NewScope returns a new, empty scope contained in the given parent
scope, if any. The comment is for debugging only.
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.
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.
NewSlice returns a new slice type for the given element type.
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.
NewTerm returns a new union term.
NewTuple returns a new tuple for the given variables.
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.
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.
NewUnion returns a new [Union] type with the given terms.
It is an error to create an empty union; they are syntactically not possible.
NewVar returns a new variable.
The arguments set the attributes found with all Objects.
ObjectString returns the string form of obj.
The Qualifier controls the printing of
package-level objects, and may be nil.
RelativeTo returns a [Qualifier] that fully qualifies members of
all packages other than pkg.
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.
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"
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".
TypeString returns the string representation of typ.
The [Qualifier] controls the printing of
package-level objects, and may be nil.
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.
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.
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.
WriteType writes the string representation of typ to buf.
The [Qualifier] controls the printing of
package-level objects, and may be nil.
Package-Level Variables (total 3)
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").
The Universe scope contains all predeclared objects of Go.
It is the outermost scope of any chain of nested scopes.
The Unsafe package is the package returned by an importer
for the import path "unsafe".
The pages are generated with Goldsv0.7.0-preview. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds.