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 language
object (Object) it denotes. Use Info.{Defs,Uses,Implicits} for the results of
name resolution.

Constant folding computes the exact constant value (constant.Value) for every
expression (ast.Expr) that is a compile-time constant. Use
Info.Types[expr].Value for the results of constant folding.

Type inference computes the type (Type) of every expression (ast.Expr) and
checks for compliance with the language specification. Use Info.Types[expr].Type
for the results of type inference.

For a tutorial, see https://golang.org/s/types-tutorial.

Index

Package files

api.go builtins.go check.go decl.go eval.go exprstring.go labels.go methodset.go objset.go ordering.go predicates.go return.go selection.go stmt.go typestring.go universe.go

Variables

  1. var Typ = []*{
  2. Invalid: {, 0, "invalid type"},
  3.  
  4. Bool: {, IsBoolean, "bool"},
  5. : {Int, , "int"},
  6. Int8: {, IsInteger, "int8"},
  7. : {Int16, , "int16"},
  8. Int32: {, IsInteger, "int32"},
  9. : {Int64, , "int64"},
  10. Uint: {, IsInteger | , "uint"},
  11. Uint8: {, IsInteger | , "uint8"},
  12. Uint16: {, IsInteger | , "uint16"},
  13. Uint32: {, IsInteger | , "uint32"},
  14. Uint64: {, IsInteger | , "uint64"},
  15. Uintptr: {, IsInteger | , "uintptr"},
  16. Float32: {, IsFloat, "float32"},
  17. : {Float64, , "float64"},
  18. Complex64: {, IsComplex, "complex64"},
  19. : {Complex128, , "complex128"},
  20. String: {, IsString, "string"},
  21. : {UnsafePointer, 0, "Pointer"},
  22.  
  23. : {UntypedBool, | IsUntyped, "untyped bool"},
  24. : {UntypedInt, | IsUntyped, "untyped int"},
  25. : {UntypedRune, | IsUntyped, "untyped rune"},
  26. : {UntypedFloat, | IsUntyped, "untyped float"},
  27. : {UntypedComplex, | IsUntyped, "untyped complex"},
  28. : {UntypedString, | IsUntyped, "untyped string"},
  29. : {UntypedNil, , "untyped nil"},
  30. }

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”).

func AssertableTo

  1. func AssertableTo(V *Interface, T ) bool

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

func

  1. func AssignableTo(V, T ) bool

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

func

  1. func Comparable(T ) bool

Comparable reports whether values of type T are comparable.

func

  1. func ConvertibleTo(V, T ) bool

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

func

  1. func DefPredeclaredTestFuncs()

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

func

  1. func ExprString(x .Expr)

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. func Id(pkg *Package, name ) string

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

func

  1. func Identical(x, y ) bool

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

func

  1. func IdenticalIgnoreTags(x, y ) bool

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

func

  1. func Implements(V , T *Interface)

Implements reports whether type V implements interface T.

func IsInterface

  1. func IsInterface(typ Type)

IsInterface reports whether typ is an interface type.

func ObjectString

  1. func ObjectString(obj Object, qf ) string

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

func

  1. func SelectionString(s *, qf Qualifier)

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

Examples:

  1. "field (T) f int"
  2. "method (T) f(X) Y"
  3. "method expr (T) f(X) Y"

func TypeString

  1. func TypeString(typ Type, qf ) string

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

func

  1. func WriteExpr(buf *.Buffer, x .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

  1. func WriteSignature(buf *.Buffer, sig *, 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.

  1. func WriteType(buf *.Buffer, typ , 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

  1. type Array struct {
  2. // contains filtered or unexported fields
  3. }

An Array represents an array type.

func

  1. func NewArray(elem , len int64) *

NewArray returns a new array type for the given element type and length.

func (*Array) Elem

  1. func (a *Array) Elem()

Elem returns element type of array a.

func (*Array) Len

  1. func (a *Array) Len()

Len returns the length of array a.

func (*Array) String

  1. func (t *Array) String()

func (*Array) Underlying

  1. func (t *Array) Underlying()

type Basic

  1. type Basic struct {
  2. // contains filtered or unexported fields
  3. }

A Basic represents a basic type.

func (*Basic) Info

  1. func (b *Basic) Info()

Info returns information about properties of basic type b.

func (*Basic) Kind

  1. func (b *Basic) Kind()

Kind returns the kind of basic type b.

func (*Basic) Name

  1. func (b *Basic) Name()

Name returns the name of basic type b.

func (*Basic) String

  1. func (t *Basic) String()

func (*Basic) Underlying

  1. func (t *Basic) Underlying()

type BasicInfo

  1. type BasicInfo int

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

  1. const (
  2. IsBoolean = 1 << iota
  3. IsInteger
  4. IsUnsigned
  5. IsFloat
  6. IsComplex
  7. IsString
  8. IsUntyped
  9.  
  10. IsOrdered = | IsFloat |
  11. IsNumeric = IsInteger | | IsComplex
  12. IsConstType = | IsNumeric |
  13. )

Properties of basic types.

type BasicKind

  1. type BasicKind int

BasicKind describes the kind of basic type.

  1. const (
  2. Invalid = iota // type is invalid
  3.  
  4. // predeclared types
  5. Bool
  6. Int
  7. Int8
  8. Int16
  9. Int32
  10. Int64
  11. Uint
  12. Uint8
  13. Uint16
  14. Uint32
  15. Uint64
  16. Uintptr
  17. Float32
  18. Float64
  19. Complex64
  20. Complex128
  21. String
  22. UnsafePointer
  23.  
  24. // types for untyped values
  25. UntypedBool
  26. UntypedRune
  27. UntypedFloat
  28. UntypedComplex
  29. UntypedString
  30. UntypedNil
  31.  
  32. // aliases
  33. Byte =
  34. Rune = Int32
  35. )

type

  1. type Builtin struct {
  2. // contains filtered or unexported fields
  3. }

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

func (*Builtin)

  1. func (obj *) Exported() bool

func (*Builtin)

  1. func (obj *) Id() string

func (*Builtin)

  1. func (obj *) Name() string

func (*Builtin)

  1. func (obj *) Parent() *Scope

func (*Builtin)

  1. func (obj *) Pkg() *Package

func (*Builtin)

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

func (*Builtin) String

  1. func (obj *Builtin) String()

func (*Builtin) Type

  1. func (obj *Builtin) Type()

type Chan

  1. type Chan struct {
  2. // contains filtered or unexported fields
  3. }

A Chan represents a channel type.

func NewChan

  1. func NewChan(dir ChanDir, elem ) *Chan

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

func (*Chan)

  1. func (c *) Dir() ChanDir

Dir returns the direction of channel c.

func (*Chan)

  1. func (c *) Elem() Type

Elem returns the element type of channel c.

func (*Chan)

  1. func (t *) String() string

func (*Chan)

  1. func (t *) Underlying() Type

type

  1. type ChanDir

A ChanDir value indicates a channel direction.

  1. const (
  2. SendRecv ChanDir =
  3. SendOnly
  4. RecvOnly
  5. )

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

type Checker

  1. type Checker struct {
  2. *Info
  3. // contains filtered or unexported fields
  4. }

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

func

  1. func NewChecker(conf *, fset *token., pkg *Package, info *) *Checker

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

func (*Checker)

  1. func (check *) Files(files []*ast.) error

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

type

  1. type Config struct {
  2. // If IgnoreFuncBodies is set, function bodies are not
  3. // type-checked.
  4. IgnoreFuncBodies
  5.  
  6. // If FakeImportC is set, `import "C"` (for packages requiring Cgo)
  7. // declares an empty "C" package and errors are omitted for qualified
  8. // identifiers referring to package C (which won't find an object).
  9. // This feature is intended for the standard library cmd/api tool.
  10. //
  11. // Caution: Effects may be unpredictable due to follow-on errors.
  12. // Do not use casually!
  13. FakeImportC bool
  14.  
  15. // If Error != nil, it is called with each error found
  16. // during type checking; err has dynamic type Error.
  17. // Secondary errors (for instance, to enumerate all types
  18. // involved in an invalid recursive type declaration) have
  19. // error strings that start with a '\t' character.
  20. // If Error == nil, type-checking stops with the first
  21. // error found.
  22. Error func(err )
  23.  
  24. // An importer is used to import packages referred to from
  25. // import declarations.
  26. // If the installed importer implements ImporterFrom, the type
  27. // checker calls ImportFrom instead of Import.
  28. // The type checker reports an error if an importer is needed
  29. // but none was installed.
  30. Importer Importer
  31.  
  32. // If Sizes != nil, it provides the sizing functions for package unsafe.
  33. // Otherwise SizesFor("gc", "amd64") is used instead.
  34. Sizes
  35.  
  36. // If DisableUnusedImportCheck is set, packages are not checked
  37. // for unused imports.
  38. DisableUnusedImportCheck bool
  39. }

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

func (*Config)

  1. func (conf *) Check(path string, fset *.FileSet, files []*.File, info *) (*Package, )

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. type Const struct {
  2. // contains filtered or unexported fields
  3. }

A Const represents a declared constant.

func NewConst

  1. func NewConst(pos token., pkg *Package, name , typ Type, val .Value) *

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

func (*Const) Exported

  1. func (obj *Const) Exported()

func (*Const) Id

  1. func (obj *Const) Id()

func (*Const) Name

  1. func (obj *Const) Name()

func (*Const) Parent

  1. func (obj *Const) Parent() *

func (*Const) Pkg

  1. func (obj *Const) Pkg() *

func (*Const) Pos

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

func (*Const)

  1. func (obj *) String() string

func (*Const)

  1. func (obj *) Type() Type

func (*Const)

  1. func (obj *) Val() constant.

type Error

  1. type Error struct {
  2. Fset *token. // file set for interpretation of Pos
  3. Pos token. // error position
  4. Msg string // error message
  5. Soft // if set, error is "soft"
  6. }

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.

func (Error) Error

  1. func (err Error) Error()

Error returns an error string formatted as follows: filenamecolumn:
message

type Func

  1. type Func struct {
  2. // contains filtered or unexported fields
  3. }

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.

func MissingMethod

  1. func MissingMethod(V Type, T *, static bool) (method *, 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.

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

  1. func NewFunc(pos .Pos, pkg *, name string, sig *) *Func

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

func (*Func)

  1. func (obj *) Exported() bool

func (*Func)

  1. func (obj *) FullName() string

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

func (*Func)

  1. func (obj *) Id() string

func (*Func)

  1. func (obj *) Name() string

func (*Func)

  1. func (obj *) Parent() *Scope

func (*Func)

  1. func (obj *) Pkg() *Package

func (*Func)

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

func (*Func) Scope

  1. func (obj *Func) Scope() *

Scope returns the scope of the function’s body block.

func (*Func) String

  1. func (obj *Func) String()

func (*Func) Type

  1. func (obj *Func) Type()

type ImportMode

  1. type ImportMode int

ImportMode is reserved for future use.

type

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

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

  1. type ImporterFrom interface {
  2. // Importer is present for backward-compatibility. Calling
  3. // Import(path) is the same as calling ImportFrom(path, "", 0);
  4. // i.e., locally vendored packages may not be found.
  5. // The types package does not call Import if an ImporterFrom
  6. // is present.
  7.  
  8. // ImportFrom returns the imported package for the given import
  9. // path when imported by a package file located in dir.
  10. // If the import failed, besides returning an error, ImportFrom
  11. // is encouraged to cache and return a package anyway, if one
  12. // was created. This will reduce package inconsistencies and
  13. // follow-on type checker errors due to the missing package.
  14. // The mode value must be 0; it is reserved for future use.
  15. // Two calls to ImportFrom with the same path and dir must
  16. // return the same package.
  17. ImportFrom(path, dir string, mode ) (*Package, )
  18. }

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

  1. type Info struct {
  2. // Types maps expressions to their types, and for constant
  3. // expressions, also their values. Invalid expressions are
  4. // omitted.
  5. //
  6. // For (possibly parenthesized) identifiers denoting built-in
  7. // functions, the recorded signatures are call-site specific:
  8. // if the call result is not a constant, the recorded type is
  9. // an argument-specific signature. Otherwise, the recorded type
  10. // is invalid.
  11. //
  12. // The Types map does not record the type of every identifier,
  13. // only those that appear where an arbitrary expression is
  14. // permitted. For instance, the identifier f in a selector
  15. // expression x.f is found only in the Selections map, the
  16. // identifier z in a variable declaration 'var z int' is found
  17. // only in the Defs map, and identifiers denoting packages in
  18. // qualified identifiers are collected in the Uses map.
  19. Types map[.Expr]
  20.  
  21. // Defs maps identifiers to the objects they define (including
  22. // package names, dots "." of dot-imports, and blank "_" identifiers).
  23. // For identifiers that do not denote objects (e.g., the package name
  24. // in package clauses, or symbolic variables t in t := x.(type) of
  25. // type switch headers), the corresponding objects are nil.
  26. //
  27. // For an anonymous field, Defs returns the field *Var it defines.
  28. //
  29. // Invariant: Defs[id] == nil || Defs[id].Pos() == id.Pos()
  30. Defs map[*ast.]Object
  31.  
  32. // Uses maps identifiers to the objects they denote.
  33. //
  34. // For an anonymous field, Uses returns the *TypeName it denotes.
  35. //
  36. // Invariant: Uses[id].Pos() != id.Pos()
  37. Uses map[*.Ident]
  38.  
  39. // Implicits maps nodes to their implicitly declared objects, if any.
  40. // The following node and object types may appear:
  41. //
  42. // node declared object
  43. //
  44. // *ast.ImportSpec *PkgName for imports without renames
  45. // *ast.CaseClause type-specific *Var for each type switch case clause (incl. default)
  46. // *ast.Field anonymous parameter *Var
  47. //
  48. Implicits map[ast.]Object
  49.  
  50. // Selections maps selector expressions (excluding qualified identifiers)
  51. // to their corresponding selections.
  52. Selections map[*.SelectorExpr]*
  53.  
  54. // Scopes maps ast.Nodes to the scopes they define. Package scopes are not
  55. // associated with a specific node but with all files belonging to a package.
  56. // Thus, the package scope can be found in the type-checked Package object.
  57. // Scopes nest, with the Universe scope being the outermost scope, enclosing
  58. // the package scope, which contains (one or more) files scopes, which enclose
  59. // function scopes which in turn enclose statement and function literal scopes.
  60. // Note that even though package-level functions are declared in the package
  61. // scope, the function scopes are embedded in the file scope of the file
  62. // containing the function declaration.
  63. //
  64. // The following node types may appear in Scopes:
  65. //
  66. // *ast.File
  67. // *ast.FuncType
  68. // *ast.BlockStmt
  69. // *ast.IfStmt
  70. // *ast.SwitchStmt
  71. // *ast.TypeSwitchStmt
  72. // *ast.CaseClause
  73. // *ast.CommClause
  74. // *ast.ForStmt
  75. // *ast.RangeStmt
  76. //
  77. Scopes map[ast.]*Scope
  78.  
  79. // InitOrder is the list of package-level initializers in the order in which
  80. // they must be executed. Initializers referring to variables related by an
  81. // initialization dependency appear in topological order, the others appear
  82. // in source order. Variables without an initialization expression do not
  83. // appear in this list.
  84. InitOrder []*
  85. }

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.


Example:

  1. // Parse a single source file.
  2. const input = `
  3. package fib
  4. type S string
  5. var a, b, c = len(b), S(c), "hello"
  6. func fib(x int) int {
  7. if x < 2 {
  8. return x
  9. }
  10. return fib(x-1) - fib(x-2)
  11. }`
  12. fset := token.NewFileSet()
  13. f, err := parser.ParseFile(fset, "fib.go", input, 0)
  14. if err != nil {
  15. log.Fatal(err)
  16. }
  17. // Type-check the package.
  18. // We create an empty map for each kind of input
  19. // we're interested in, and Check populates them.
  20. info := types.Info{
  21. Types: make(map[ast.Expr]types.TypeAndValue),
  22. Defs: make(map[*ast.Ident]types.Object),
  23. Uses: make(map[*ast.Ident]types.Object),
  24. }
  25. var conf types.Config
  26. pkg, err := conf.Check("fib", fset, []*ast.File{f}, &info)
  27. if err != nil {
  28. log.Fatal(err)
  29. }
  30. // Print package-level variables in initialization order.
  31. fmt.Printf("InitOrder: %v\n\n", info.InitOrder)
  32. // For each named object, print the line and
  33. // column of its definition and each of its uses.
  34. fmt.Println("Defs and Uses of each named object:")
  35. usesByObj := make(map[types.Object][]string)
  36. for id, obj := range info.Uses {
  37. posn := fset.Position(id.Pos())
  38. lineCol := fmt.Sprintf("%d:%d", posn.Line, posn.Column)
  39. usesByObj[obj] = append(usesByObj[obj], lineCol)
  40. }
  41. var items []string
  42. for obj, uses := range usesByObj {
  43. sort.Strings(uses)
  44. item := fmt.Sprintf("%s:\n defined at %s\n used at %s",
  45. types.ObjectString(obj, types.RelativeTo(pkg)),
  46. fset.Position(obj.Pos()),
  47. strings.Join(uses, ", "))
  48. items = append(items, item)
  49. }
  50. sort.Strings(items) // sort by line:col, in effect
  51. fmt.Println(strings.Join(items, "\n"))
  52. fmt.Println()
  53. fmt.Println("Types and Values of each expression:")
  54. items = nil
  55. for expr, tv := range info.Types {
  56. var buf bytes.Buffer
  57. posn := fset.Position(expr.Pos())
  58. tvstr := tv.Type.String()
  59. if tv.Value != nil {
  60. tvstr += " = " + tv.Value.String()
  61. }
  62. // line:col | expr | mode : type = value
  63. fmt.Fprintf(&buf, "%2d:%2d | %-19s | %-7s : %s",
  64. posn.Line, posn.Column, exprString(fset, expr),
  65. mode(tv), tvstr)
  66. items = append(items, buf.String())
  67. }
  68. sort.Strings(items)
  69. fmt.Println(strings.Join(items, "\n"))
  70. // Output:
  71. // InitOrder: [c = "hello" b = S(c) a = len(b)]
  72. //
  73. // Defs and Uses of each named object:
  74. // builtin len:
  75. // defined at -
  76. // used at 6:15
  77. // func fib(x int) int:
  78. // defined at fib.go:8:6
  79. // used at 12:20, 12:9
  80. // type S string:
  81. // used at 6:23
  82. // type int:
  83. // defined at -
  84. // used at 8:12, 8:17
  85. // type string:
  86. // defined at -
  87. // used at 4:8
  88. // var b S:
  89. // defined at fib.go:6:8
  90. // used at 6:19
  91. // var c string:
  92. // defined at fib.go:6:11
  93. // used at 6:25
  94. // var x int:
  95. // defined at fib.go:8:10
  96. // used at 10:10, 12:13, 12:24, 9:5
  97. //
  98. // Types and Values of each expression:
  99. // 4: 8 | string | type : string
  100. // 6:15 | len | builtin : func(string) int
  101. // 6:15 | len(b) | value : int
  102. // 6:19 | b | var : fib.S
  103. // 6:23 | S | type : fib.S
  104. // 6:23 | S(c) | value : fib.S
  105. // 6:25 | c | var : string
  106. // 6:29 | "hello" | value : string = "hello"
  107. // 8:12 | int | type : int
  108. // 8:17 | int | type : int
  109. // 9: 5 | x | var : int
  110. // 9: 5 | x < 2 | value : untyped bool
  111. // 9: 9 | 2 | value : int = 2
  112. // 10:10 | x | var : int
  113. // 12: 9 | fib | value : func(x int) int
  114. // 12: 9 | fib(x - 1) | value : int
  115. // 12: 9 | fib(x-1) - fib(x-2) | value : int
  116. // 12:13 | x | var : int
  117. // 12:13 | x - 1 | value : int
  118. // 12:15 | 1 | value : int = 1
  119. // 12:20 | fib | value : func(x int) int
  120. // 12:20 | fib(x - 2) | value : int
  121. // 12:24 | x | var : int
  122. // 12:24 | x - 2 | value : int
  123. // 12:26 | 2 | value : int = 2

func (*Info)

  1. func (info *) ObjectOf(id *ast.) Object

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

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

Precondition: the Uses and Defs maps are populated.

func (*Info)

  1. func (info *) TypeOf(e ast.) Type

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

type

  1. type Initializer struct {
  2. Lhs []* // var Lhs = Rhs
  3. Rhs ast.
  4. }

func (*Initializer) String

  1. func (init *Initializer) String()

type Interface

An Interface represents an interface type.

func NewInterface

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

NewInterface returns a new (incomplete) interface for the given methods and
embedded types. To compute the method set of the interface, Complete must be
called.

func (*Interface)

  1. func (t *) Complete() *Interface

Complete computes the interface’s method set. It must be called by users of
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. Complete
returns the receiver.

func (*Interface)

  1. func (t *) Embedded(i int) *

Embedded returns the i’th embedded type of interface t for 0 <= i <
t.NumEmbeddeds(). The types are ordered by the corresponding TypeName’s unique
Id.

func (*Interface) Empty

  1. func (t *Interface) Empty()

Empty returns true if t is the empty interface.

func (*Interface) ExplicitMethod

  1. func (t *Interface) ExplicitMethod(i ) *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)

  1. func (t *) Method(i int) *

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. func (t *Interface) NumEmbeddeds()

NumEmbeddeds returns the number of embedded types in interface t.

func (*Interface) NumExplicitMethods

  1. func (t *Interface) NumExplicitMethods()

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

func (*Interface) NumMethods

  1. func (t *Interface) NumMethods()

NumMethods returns the total number of methods of interface t.

func (*Interface) String

  1. func (t *Interface) String()

func (*Interface) Underlying

  1. func (t *Interface) Underlying()

type Label

  1. // contains filtered or unexported fields
  2. }

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

func NewLabel

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

NewLabel returns a new label.

func (*Label)

  1. func (obj *) Exported() bool

func (*Label)

  1. func (obj *) Id() string

func (*Label)

  1. func (obj *) Name() string

  1. func (obj *) Parent() *Scope

func (*Label)

  1. func (obj *) Pkg() *Package

func (*Label)

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

func (*Label) String

  1. func (obj *Label) String()

func (*Label) Type

  1. func (obj *Label) Type()

  1. type Map struct {
  2. // contains filtered or unexported fields
  3. }

A Map represents a map type.

func NewMap

  1. func NewMap(key, elem Type) *

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

func (*Map) Elem

  1. func (m *Map) Elem()

Elem returns the element type of map m.

func (*Map) Key

  1. func (m *Map) Key()

Key returns the key type of map m.

func (*Map) String

  1. func (t *Map) String()

func (*Map) Underlying

  1. func (t *Map) Underlying()

type MethodSet

  1. type MethodSet struct {
  2. // contains filtered or unexported fields
  3. }

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.


Example:

  1. // Parse a single source file.
  2. const input = `
  3. package temperature
  4. import "fmt"
  5. type Celsius float64
  6. func (c Celsius) String() string { return fmt.Sprintf("%g°C", c) }
  7. func (c *Celsius) SetF(f float64) { *c = Celsius(f - 32 / 9 * 5) }
  8. `
  9. fset := token.NewFileSet()
  10. f, err := parser.ParseFile(fset, "celsius.go", input, 0)
  11. if err != nil {
  12. log.Fatal(err)
  13. }
  14. // Type-check a package consisting of this file.
  15. // Type information for the imported packages
  16. // comes from $GOROOT/pkg/$GOOS_$GOOARCH/fmt.a.
  17. conf := types.Config{Importer: importer.Default()}
  18. pkg, err := conf.Check("temperature", fset, []*ast.File{f}, nil)
  19. if err != nil {
  20. log.Fatal(err)
  21. }
  22. // Print the method sets of Celsius and *Celsius.
  23. celsius := pkg.Scope().Lookup("Celsius").Type()
  24. for _, t := range []types.Type{celsius, types.NewPointer(celsius)} {
  25. fmt.Printf("Method set of %s:\n", t)
  26. mset := types.NewMethodSet(t)
  27. for i := 0; i < mset.Len(); i++ {
  28. fmt.Println(mset.At(i))
  29. }
  30. fmt.Println()
  31. }
  32. // Output:
  33. // Method set of temperature.Celsius:
  34. // method (temperature.Celsius) String() string
  35. //
  36. // Method set of *temperature.Celsius:
  37. // method (*temperature.Celsius) SetF(f float64)
  38. // method (*temperature.Celsius) String() string

func

  1. func NewMethodSet(T ) *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)

  1. func (s *) At(i int) *

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

func (*MethodSet) Len

  1. func (s *MethodSet) Len()

Len returns the number of methods in s.

func (*MethodSet) Lookup

  1. func (s *MethodSet) Lookup(pkg *, name string) *

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

func (*MethodSet) String

  1. func (s *MethodSet) String()

type Named

  1. type Named struct {
  2. // contains filtered or unexported fields
  3. }

A Named represents a named type.

func NewNamed

  1. func NewNamed(obj *TypeName, underlying , methods []*Func) *

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. func (t *Named) AddMethod(m *)

AddMethod adds method m unless it is already in the method list.

func (*Named) Method

  1. func (t *Named) Method(i ) *Func

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

func (*Named)

  1. func (t *) NumMethods() int

NumMethods returns the number of explicit methods whose receiver is named type
t.

func (*Named)

  1. func (t *) Obj() *TypeName

Obj returns the type name for the named type t.

func (*Named)

  1. func (t *) SetUnderlying(underlying Type)

SetUnderlying sets the underlying type and marks t as complete.

func (*Named)

  1. func (t *) String() string

func (*Named)

  1. func (t *) Underlying() Type

type

  1. type Nil struct {
  2. // contains filtered or unexported fields
  3. }

Nil represents the predeclared value nil.

func (*Nil)

  1. func (obj *) Exported() bool

func (*Nil)

  1. func (obj *) Id() string

func (*Nil)

  1. func (obj *) Name() string

func (*Nil)

  1. func (obj *) Parent() *Scope

func (*Nil)

  1. func (obj *) Pkg() *Package

func (*Nil)

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

func (*Nil) String

  1. func (obj *Nil) String()

func (*Nil) Type

  1. func (obj *Nil) Type()

type Object

  1. type Object interface {
  2. Parent() *Scope // scope in which this object is declared; nil for methods and struct fields
  3. Pos() .Pos // position of object identifier in declaration
  4. Pkg() * // package to which this object belongs; nil for labels and objects in the Universe scope
  5. Name() string // package local object name
  6. Type() // object type
  7. Exported() bool // reports whether the name starts with a capital letter
  8. Id() // object name if exported, qualified name if not exported (see func Id)
  9.  
  10. // String returns a human-readable string of the object.
  11. String() string
  12. // contains filtered or unexported methods
  13. }

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.

func

  1. func LookupFieldOrMethod(T , addressable bool, pkg *, name string) (obj , index []int, indirect )

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).

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

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

The earlier index entries are the indices of the anonymous 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:

  1. - If index != nil, the index sequence points to an ambiguous entry
  2. (the same name appeared more than once at the same embedding level).
  3. - If indirect is set, a method with a pointer receiver type was found
  4. the method's formal receiver base type, nor was the receiver addressable.

type Package

  1. type Package struct {
  2. // contains filtered or unexported fields
  3. }

A Package describes a Go package.

func NewPackage

  1. func NewPackage(path, name string) *

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. func (pkg *Package) Complete()

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

func (*Package) Imports

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

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.

func (*Package) MarkComplete

  1. func (pkg *Package) MarkComplete()

MarkComplete marks a package as complete.

func (*Package)

  1. func (pkg *) Name() string

Name returns the package name.

func (*Package)

  1. func (pkg *) Path() string

Path returns the package path.

func (*Package)

  1. func (pkg *) Scope() *Scope

Scope returns the (complete or incomplete) package scope holding the objects
declared at package level (TypeNames, Consts, Vars, and Funcs).

func (*Package)

  1. func (pkg *) 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)

  1. func (pkg *) SetName(name string)

SetName sets the package name.

func (*Package)

  1. func (pkg *) String() string

type

  1. type PkgName struct {
  2. // contains filtered or unexported fields
  3. }

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

func

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

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

func (*PkgName)

  1. func (obj *) Exported() bool

func (*PkgName)

  1. func (obj *) Id() string

func (*PkgName)

  1. func (obj *) Imported() *Package

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

func (*PkgName)

  1. func (obj *) Name() string

func (*PkgName)

  1. func (obj *) Parent() *Scope

func (*PkgName)

  1. func (obj *) Pkg() *Package

func (*PkgName)

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

func (*PkgName) String

  1. func (obj *PkgName) String()

func (*PkgName) Type

  1. func (obj *PkgName) Type()

type Pointer

  1. type Pointer struct {
  2. // contains filtered or unexported fields
  3. }

A Pointer represents a pointer type.

func NewPointer

  1. func NewPointer(elem Type) *

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

func (*Pointer) Elem

  1. func (p *Pointer) Elem()

Elem returns the element type for the given pointer p.

func (*Pointer) String

  1. func (t *Pointer) String()

func (*Pointer) Underlying

  1. func (t *Pointer) Underlying()

type Qualifier

  1. type Qualifier func(*Package)

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

  1. func RelativeTo(pkg *Package)

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

type Scope

  1. type Scope struct {
  2. // contains filtered or unexported fields
  3. }

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.


Example:

  1. // Parse the source files for a package.
  2. fset := token.NewFileSet()
  3. var files []*ast.File
  4. for _, file := range []struct{ name, input string }{
  5. {"main.go", `
  6. package main
  7. import "fmt"
  8. func main() {
  9. freezing := FToC(-18)
  10. fmt.Println(freezing, Boiling) }
  11. `},
  12. {"celsius.go", `
  13. package main
  14. import "fmt"
  15. type Celsius float64
  16. func (c Celsius) String() string { return fmt.Sprintf("%g°C", c) }
  17. func FToC(f float64) Celsius { return Celsius(f - 32 / 9 * 5) }
  18. const Boiling Celsius = 100
  19. `},
  20. } {
  21. f, err := parser.ParseFile(fset, file.name, file.input, 0)
  22. if err != nil {
  23. log.Fatal(err)
  24. }
  25. files = append(files, f)
  26. }
  27. // Type-check a package consisting of these files.
  28. // Type information for the imported "fmt" package
  29. // comes from $GOROOT/pkg/$GOOS_$GOOARCH/fmt.a.
  30. conf := types.Config{Importer: importer.Default()}
  31. pkg, err := conf.Check("temperature", fset, files, nil)
  32. if err != nil {
  33. log.Fatal(err)
  34. }
  35. // Print the tree of scopes.
  36. // For determinism, we redact addresses.
  37. var buf bytes.Buffer
  38. pkg.Scope().WriteTo(&buf, 0, true)
  39. rx := regexp.MustCompile(` 0x[a-fA-F0-9]*`)
  40. fmt.Println(rx.ReplaceAllString(buf.String(), ""))
  41. // Output:
  42. // package "temperature" scope {
  43. // . const temperature.Boiling temperature.Celsius
  44. // . type temperature.Celsius float64
  45. // . func temperature.FToC(f float64) temperature.Celsius
  46. // . func temperature.main()
  47. //
  48. // . main.go scope {
  49. // . . package fmt
  50. //
  51. // . . function scope {
  52. // . . . var freezing temperature.Celsius
  53. // . . }. }
  54. // . celsius.go scope {
  55. // . . package fmt
  56. //
  57. // . . function scope {
  58. // . . . var c temperature.Celsius
  59. // . . }
  60. // . . function scope {
  61. // . . . var f float64
  62. // . . }. }}

func

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

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

func (*Scope) Child

  1. func (s *Scope) Child(i ) *Scope

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

func (*Scope)

  1. func (s *) Contains(pos token.) bool

Contains returns true if 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)

  1. func (s *) End() token.

func (*Scope) Innermost

  1. func (s *Scope) Innermost(pos .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.

func (*Scope) Insert

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. func (s *Scope) Len()

Len() returns the number of scope elements.

func (*Scope) Lookup

  1. func (s *Scope) Lookup(name ) Object

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

func (*Scope)

  1. func (s *) LookupParent(name string, pos .Pos) (*, 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,
below). This can only happen for dot-imported objects whose scope is the scope
of the package that exported them.

func (*Scope)

  1. func (s *) Names() []string

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

func (*Scope)

  1. func (s *) NumChildren() int

NumChildren() returns the number of scopes nested in s.

func (*Scope)

  1. func (s *) Parent() *Scope

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

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

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. func (s *Scope) String()

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

func (*Scope) WriteTo

  1. func (s *Scope) WriteTo(w .Writer, n , 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

  1. type Selection struct {
  2. // contains filtered or unexported fields
  3. }

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

  1. type T struct{ x int; E }
  2. type E struct{}
  3. func (e E) m() {}
  4. var p *T

the following relations exist:

  1. Selector Kind Recv Obj Type Index Indirect
  2. p.x FieldVal T x int {0} true
  3. p.m MethodVal *T m func (e *T) m() {1, 0} true
  4. T.m MethodExpr T m func m(_ T) {1, 0} false

func (*Selection)

  1. func (s *) 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. 1) the list of declared methods of a named type; or
  2. 2) the list of methods of an interface type; or
  3. 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)

  1. func (s *) Indirect() bool

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

func (*Selection)

  1. func (s *) Kind() SelectionKind

Kind returns the selection kind.

func (*Selection)

  1. func (s *) 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)

  1. func (s *) Recv() Type

Recv returns the type of x in x.f.

func (*Selection)

  1. func (s *) String() string

func (*Selection)

  1. func (s *) Type() Type

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

type

  1. type SelectionKind

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

  1. const (
  2. FieldVal SelectionKind = // x.f is a struct field selector
  3. MethodVal // x.f is a method selector
  4. MethodExpr // x.f is a method expression
  5. )

type Signature

  1. type Signature struct {
  2. // contains filtered or unexported fields
  3. }

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

func NewSignature

  1. func NewSignature(recv *Var, params, results *, variadic bool) *

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.

func (*Signature) Params

  1. func (s *Signature) Params() *

Params returns the parameters of signature s, or nil.

func (*Signature) Recv

  1. func (s *Signature) Recv() *

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) Results

  1. func (s *Signature) Results() *

Results returns the results of signature s, or nil.

func (*Signature) String

  1. func (t *Signature) String()

func (*Signature) Underlying

  1. func (t *Signature) Underlying()

func (*Signature) Variadic

  1. func (s *Signature) Variadic()

Variadic reports whether the signature s is variadic.

type Sizes

  1. type Sizes interface {
  2. // Alignof returns the alignment of a variable of type T.
  3. // Alignof must implement the alignment guarantees required by the spec.
  4. Alignof(T Type)
  5.  
  6. // Offsetsof returns the offsets of the given struct fields, in bytes.
  7. // Offsetsof must implement the offset guarantees required by the spec.
  8. Offsetsof(fields []*Var) []
  9.  
  10. // Sizeof returns the size of a variable of type T.
  11. // Sizeof must implement the size guarantees required by the spec.
  12. Sizeof(T Type)
  13. }

Sizes defines the sizing functions for package unsafe.

func SizesFor

  1. func SizesFor(compiler, arch string)

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”, “arm”, “arm64”, “amd64”,
“amd64p32”, “mips”, “mipsle”, “mips64”, “mips64le”, “ppc64”, “ppc64le”, “s390x”.

type Slice

  1. type Slice struct {
  2. // contains filtered or unexported fields
  3. }

A Slice represents a slice type.

func NewSlice

  1. func NewSlice(elem Type) *

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

func (*Slice) Elem

  1. func (s *Slice) Elem()

Elem returns the element type of slice s.

func (*Slice) String

  1. func (t *Slice) String()

func (*Slice) Underlying

  1. func (t *Slice) Underlying()

type StdSizes

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

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

  1. - The size of explicitly sized basic types (int16, etc.) is the
  2. specified size.
  3. - The size of strings and interfaces is 2*WordSize.
  4. - The size of slices is 3*WordSize.
  5. - The size of an array of n elements corresponds to the size of
  6. a struct of n consecutive fields of the array's element type.
  7. - The size of a struct is the offset of the last field plus that
  8. field's size. As with all element types, if the struct is used
  9. in an array its size must first be aligned to a multiple of the
  10. struct's alignment.
  11. - All other types have size WordSize.
  12. - Arrays and structs are aligned per spec definition; all other
  13. types are naturally aligned with a maximum alignment MaxAlign.

*StdSizes implements Sizes.

func (*StdSizes) Alignof

  1. func (s *StdSizes) Alignof(T ) int64

func (*StdSizes)

  1. func (s *) Offsetsof(fields []*Var) []

func (*StdSizes) Sizeof

  1. func (s *StdSizes) Sizeof(T ) int64

type

  1. type Struct struct {
  2. // contains filtered or unexported fields
  3. }

A Struct represents a struct type.

func

  1. func NewStruct(fields []*, tags []string) *

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. func (s *Struct) Field(i ) *Var

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

func (*Struct)

  1. func (s *) NumFields() int

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

func (*Struct)

  1. func (t *) String() string

func (*Struct)

  1. func (s *) Tag(i int)

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

func (*Struct) Underlying

  1. func (t *Struct) Underlying()

type Tuple

  1. type Tuple struct {
  2. // contains filtered or unexported fields
  3. }

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.

func NewTuple

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

NewTuple returns a new tuple for the given variables.

func (*Tuple) At

  1. func (t *Tuple) At(i ) *Var

At returns the i’th variable of tuple t.

func (*Tuple)

  1. func (t *) Len() int

Len returns the number variables of tuple t.

func (*Tuple)

  1. func (t *) String() string

func (*Tuple)

  1. func (t *) Underlying() Type

type

  1. type Type interface {
  2. // Underlying returns the underlying type of a type.
  3. Underlying()
  4.  
  5. // String returns a string representation of a type.
  6. String() string
  7. }

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

func

  1. func Default(typ ) 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.

type

  1. type TypeAndValue struct {
  2. Type
  3. Value constant.
  4. // contains filtered or unexported fields
  5. }

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

func Eval

  1. func Eval(fset *token., pkg *Package, pos .Pos, expr ) (TypeAndValue, )

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.

If the expression contains function literals, their bodies are ignored (i.e.,
the bodies are not type-checked).

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
evaluated.

Note: Eval should not be used instead of running Check to compute types and
values, but in addition to Check. Eval will re-evaluate its argument each time,
and it also does not know about the context in which an expression is used
(e.g., an assignment). Thus, top- level untyped constants will return an untyped
type rather then the respective context-specific type.

func (TypeAndValue) Addressable

  1. func (tv TypeAndValue) Addressable()

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

func (TypeAndValue)

  1. func (tv ) Assignable() bool

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

func (TypeAndValue)

  1. func (tv ) HasOk() bool

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

func (TypeAndValue)

  1. func (tv ) IsBuiltin() bool

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

func (TypeAndValue)

  1. func (tv ) IsNil() bool

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

func (TypeAndValue)

  1. func (tv ) IsType() bool

IsType reports whether the corresponding expression specifies a type.

func (TypeAndValue)

  1. func (tv ) 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)

  1. func (tv ) IsVoid() bool

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

  1. type TypeName struct {
  2. // contains filtered or unexported fields
  3. }

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

func

  1. func NewTypeName(pos .Pos, pkg *, name string, typ ) *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)

  1. func (obj *) Exported() bool

func (*TypeName)

  1. func (obj *) Id() string

func (*TypeName)

  1. func (obj *) IsAlias() bool

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

func (*TypeName)

  1. func (obj *) Name() string

func (*TypeName)

  1. func (obj *) Parent() *Scope

func (*TypeName)

  1. func (obj *) Pkg() *Package

func (*TypeName)

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

func (*TypeName) String

  1. func (obj *TypeName) String()

func (*TypeName) Type

  1. func (obj *TypeName) Type()

type Var

  1. type Var struct {
  2. // contains filtered or unexported fields
  3. }

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

func NewField

  1. func NewField(pos token., pkg *Package, name , typ Type, anonymous ) *Var

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

func

  1. func NewParam(pos .Pos, pkg *, name string, typ ) *Var

NewParam returns a new variable representing a function parameter.

func

  1. func NewVar(pos .Pos, pkg *, name string, typ ) *Var

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

func (*Var)

  1. func (obj *) Anonymous() bool

Anonymous reports whether the variable is an anonymous field.

func (*Var)

  1. func (obj *) Exported() bool

func (*Var)

  1. func (obj *) Id() string

func (*Var)

  1. func (obj *) IsField() bool

IsField reports whether the variable is a struct field.

func (*Var)

  1. func (obj *) Name() string

func (*Var)

  1. func (obj *) Parent() *Scope

func (*Var)

  1. func (obj *) Pkg() *Package

func (*Var)

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

func (*Var) String

  1. func (obj *Var) String()

func (*Var) Type

  1. func (obj *Var) Type()