目录 搜索
archive archive/tar archive/zip bufio bufio(缓存) builtin builtin(内置包) bytes bytes(包字节) compress compress/bzip2(压缩/bzip2) compress/flate(压缩/flate) compress/gzip(压缩/gzip) compress/lzw(压缩/lzw) compress/zlib(压缩/zlib) container container/heap(容器数据结构heap) container/list(容器数据结构list) container/ring(容器数据结构ring) context context(上下文) crypto crypto(加密) crypto/aes(加密/aes) crypto/cipher(加密/cipher) crypto/des(加密/des) crypto/dsa(加密/dsa) crypto/ecdsa(加密/ecdsa) crypto/elliptic(加密/elliptic) crypto/hmac(加密/hmac) crypto/md5(加密/md5) crypto/rand(加密/rand) crypto/rc4(加密/rc4) crypto/rsa(加密/rsa) crypto/sha1(加密/sha1) crypto/sha256(加密/sha256) crypto/sha512(加密/sha512) crypto/subtle(加密/subtle) crypto/tls(加密/tls) crypto/x509(加密/x509) crypto/x509/pkix(加密/x509/pkix) database database/sql(数据库/sql) database/sql/driver(数据库/sql/driver) debug debug/dwarf(调试/dwarf) debug/elf(调试/elf) debug/gosym(调试/gosym) debug/macho(调试/macho) debug/pe(调试/pe) debug/plan9obj(调试/plan9obj) encoding encoding(编码) encoding/ascii85(编码/ascii85) encoding/asn1(编码/asn1) encoding/base32(编码/base32) encoding/base64(编码/base64) encoding/binary(编码/binary) encoding/csv(编码/csv) encoding/gob(编码/gob) encoding/hex(编码/hex) encoding/json(编码/json) encoding/pem(编码/pem) encoding/xml(编码/xml) errors errors(错误) expvar expvar flag flag(命令行参数解析flag包) fmt fmt go go/ast(抽象语法树) go/build go/constant(常量) go/doc(文档) go/format(格式) go/importer go/parser go/printer go/scanner(扫描仪) go/token(令牌) go/types(类型) hash hash(散列) hash/adler32 hash/crc32 hash/crc64 hash/fnv html html html/template(模板) image image(图像) image/color(颜色) image/color/palette(调色板) image/draw(绘图) image/gif image/jpeg image/png index index/suffixarray io io io/ioutil log log log/syslog(日志系统) math math math/big math/big math/bits math/bits math/cmplx math/cmplx math/rand math/rand mime mime mime/multipart(多部分) mime/quotedprintable net net net/http net/http net/http/cgi net/http/cookiejar net/http/fcgi net/http/httptest net/http/httptrace net/http/httputil net/http/internal net/http/pprof net/mail net/mail net/rpc net/rpc net/rpc/jsonrpc net/smtp net/smtp net/textproto net/textproto net/url net/url os os os/exec os/signal os/user path path path/filepath(文件路径) plugin plugin(插件) reflect reflect(反射) regexp regexp(正则表达式) regexp/syntax runtime runtime(运行时) runtime/debug(调试) runtime/internal/sys runtime/pprof runtime/race(竞争) runtime/trace(执行追踪器) sort sort(排序算法) strconv strconv(转换) strings strings(字符串) sync sync(同步) sync/atomic(原子操作) syscall syscall(系统调用) testing testing(测试) testing/iotest testing/quick text text/scanner(扫描文本) text/tabwriter text/template(定义模板) text/template/parse time time(时间戳) unicode unicode unicode/utf16 unicode/utf8 unsafe unsafe
文字

  • import "go/types"

  • Overview

  • Index

  • Examples

概观

包类型声明数据类型并实现Go包的类型检查算法。使用Config.Check来调用包的类型检查器。或者,使用NewChecker创建一个新的类型检查器,并通过调用Checker.Files来递增调用它。

类型检查由几个相互依赖的阶段组成:

名称解析将程序中的每个标识符(ast.Ident)映射到它表示的语言对象(Object)。使用Info。{Defs,Uses,Implicits}来获得名称解析的结果。

常量折叠计算每个表达式(ast.Expr)的精确常量值(constant.Value),这是一个编译时常量。使用Info.Typesexpr.Value获取常量折叠的结果。

类型推断计算每个表达式(ast.Expr)的类型(Type)并检查是否符合语言规范。使用Info.Typesexpr.Type作为类型推断的结果。

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

索引

  • Variables

  • func AssertableTo(V *Interface, T Type) bool

  • func AssignableTo(V, T Type) bool

  • func Comparable(T Type) bool

  • func ConvertibleTo(V, T Type) bool

  • func DefPredeclaredTestFuncs()

  • func ExprString(x ast.Expr) string

  • func Id(pkg *Package, name string) string

  • func Identical(x, y Type) bool

  • func IdenticalIgnoreTags(x, y Type) bool

  • func Implements(V Type, T *Interface) bool

  • func IsInterface(typ Type) bool

  • func ObjectString(obj Object, qf Qualifier) string

  • func SelectionString(s *Selection, qf Qualifier) string

  • func TypeString(typ Type, qf Qualifier) string

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

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

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

  • type Array

  • func NewArray(elem Type, len int64) *Array

  • func (a *Array) Elem() Type

  • func (a *Array) Len() int64

  • func (t *Array) String() string

  • func (t *Array) Underlying() Type

  • type Basic

  • func (b *Basic) Info() BasicInfo

  • func (b *Basic) Kind() BasicKind

  • func (b *Basic) Name() string

  • func (t *Basic) String() string

  • func (t *Basic) Underlying() Type

  • type BasicInfo

  • type BasicKind

  • type Builtin

  • func (obj *Builtin) Exported() bool

  • func (obj *Builtin) Id() string

  • func (obj *Builtin) Name() string

  • func (obj *Builtin) Parent() *Scope

  • func (obj *Builtin) Pkg() *Package

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

  • func (obj *Builtin) String() string

  • func (obj *Builtin) Type() Type

  • type Chan

  • func NewChan(dir ChanDir, elem Type) *Chan

  • func (c *Chan) Dir() ChanDir

  • func (c *Chan) Elem() Type

  • func (t *Chan) String() string

  • func (t *Chan) Underlying() Type

  • type ChanDir

  • type Checker

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

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

  • type Config

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

  • type Const

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

  • func (obj *Const) Exported() bool

  • func (obj *Const) Id() string

  • func (obj *Const) Name() string

  • func (obj *Const) Parent() *Scope

  • func (obj *Const) Pkg() *Package

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

  • func (obj *Const) String() string

  • func (obj *Const) Type() Type

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

  • type Error

  • func (err Error) Error() string

  • type Func

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

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

  • func (obj *Func) Exported() bool

  • func (obj *Func) FullName() string

  • func (obj *Func) Id() string

  • func (obj *Func) Name() string

  • func (obj *Func) Parent() *Scope

  • func (obj *Func) Pkg() *Package

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

  • func (obj *Func) Scope() *Scope

  • func (obj *Func) String() string

  • func (obj *Func) Type() Type

  • type ImportMode

  • type Importer

  • type ImporterFrom

  • type Info

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

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

  • type Initializer

  • func (init *Initializer) String() string

  • type Interface

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

  • func (t *Interface) Complete() *Interface

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

  • func (t *Interface) Empty() bool

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

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

  • func (t *Interface) NumEmbeddeds() int

  • func (t *Interface) NumExplicitMethods() int

  • func (t *Interface) NumMethods() int

  • func (t *Interface) String() string

  • func (t *Interface) Underlying() Type

  • type Label

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

  • func (obj *Label) Exported() bool

  • func (obj *Label) Id() string

  • func (obj *Label) Name() string

  • func (obj *Label) Parent() *Scope

  • func (obj *Label) Pkg() *Package

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

  • func (obj *Label) String() string

  • func (obj *Label) Type() Type

  • type Map

  • func NewMap(key, elem Type) *Map

  • func (m *Map) Elem() Type

  • func (m *Map) Key() Type

  • func (t *Map) String() string

  • func (t *Map) Underlying() Type

  • type MethodSet

  • func NewMethodSet(T Type) *MethodSet

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

  • func (s *MethodSet) Len() int

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

  • func (s *MethodSet) String() string

  • type Named

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

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

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

  • func (t *Named) NumMethods() int

  • func (t *Named) Obj() *TypeName

  • func (t *Named) SetUnderlying(underlying Type)

  • func (t *Named) String() string

  • func (t *Named) Underlying() Type

  • type Nil

  • func (obj *Nil) Exported() bool

  • func (obj *Nil) Id() string

  • func (obj *Nil) Name() string

  • func (obj *Nil) Parent() *Scope

  • func (obj *Nil) Pkg() *Package

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

  • func (obj *Nil) String() string

  • func (obj *Nil) Type() Type

  • type Object

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

  • type Package

  • func NewPackage(path, name string) *Package

  • func (pkg *Package) Complete() bool

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

  • func (pkg *Package) MarkComplete()

  • func (pkg *Package) Name() string

  • func (pkg *Package) Path() string

  • func (pkg *Package) Scope() *Scope

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

  • func (pkg *Package) SetName(name string)

  • func (pkg *Package) String() string

  • type PkgName

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

  • func (obj *PkgName) Exported() bool

  • func (obj *PkgName) Id() string

  • func (obj *PkgName) Imported() *Package

  • func (obj *PkgName) Name() string

  • func (obj *PkgName) Parent() *Scope

  • func (obj *PkgName) Pkg() *Package

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

  • func (obj *PkgName) String() string

  • func (obj *PkgName) Type() Type

  • type Pointer

  • func NewPointer(elem Type) *Pointer

  • func (p *Pointer) Elem() Type

  • func (t *Pointer) String() string

  • func (t *Pointer) Underlying() Type

  • type Qualifier

  • func RelativeTo(pkg *Package) Qualifier

  • type Scope

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

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

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

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

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

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

  • func (s *Scope) Len() int

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

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

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

  • func (s *Scope) NumChildren() int

  • func (s *Scope) Parent() *Scope

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

  • func (s *Scope) String() string

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

  • type Selection

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

  • func (s *Selection) Indirect() bool

  • func (s *Selection) Kind() SelectionKind

  • func (s *Selection) Obj() Object

  • func (s *Selection) Recv() Type

  • func (s *Selection) String() string

  • func (s *Selection) Type() Type

  • type SelectionKind

  • type Signature

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

  • func (s *Signature) Params() *Tuple

  • func (s *Signature) Recv() *Var

  • func (s *Signature) Results() *Tuple

  • func (t *Signature) String() string

  • func (t *Signature) Underlying() Type

  • func (s *Signature) Variadic() bool

  • type Sizes

  • func SizesFor(compiler, arch string) Sizes

  • type Slice

  • func NewSlice(elem Type) *Slice

  • func (s *Slice) Elem() Type

  • func (t *Slice) String() string

  • func (t *Slice) Underlying() Type

  • type StdSizes

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

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

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

  • type Struct

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

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

  • func (s *Struct) NumFields() int

  • func (t *Struct) String() string

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

  • func (t *Struct) Underlying() Type

  • type Tuple

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

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

  • func (t *Tuple) Len() int

  • func (t *Tuple) String() string

  • func (t *Tuple) Underlying() Type

  • type Type

  • func Default(typ Type) Type

  • type TypeAndValue

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

  • func (tv TypeAndValue) Addressable() bool

  • func (tv TypeAndValue) Assignable() bool

  • func (tv TypeAndValue) HasOk() bool

  • func (tv TypeAndValue) IsBuiltin() bool

  • func (tv TypeAndValue) IsNil() bool

  • func (tv TypeAndValue) IsType() bool

  • func (tv TypeAndValue) IsValue() bool

  • func (tv TypeAndValue) IsVoid() bool

  • type TypeName

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

  • func (obj *TypeName) Exported() bool

  • func (obj *TypeName) Id() string

  • func (obj *TypeName) IsAlias() bool

  • func (obj *TypeName) Name() string

  • func (obj *TypeName) Parent() *Scope

  • func (obj *TypeName) Pkg() *Package

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

  • func (obj *TypeName) String() string

  • func (obj *TypeName) Type() Type

  • type Var

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

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

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

  • func (obj *Var) Anonymous() bool

  • func (obj *Var) Exported() bool

  • func (obj *Var) Id() string

  • func (obj *Var) IsField() bool

  • func (obj *Var) Name() string

  • func (obj *Var) Parent() *Scope

  • func (obj *Var) Pkg() *Package

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

  • func (obj *Var) String() string

  • func (obj *Var) Type() Type

例子

Info MethodSet Scope

包文件

api.go assignments.go builtins.go call.go check.go conversions.go decl.go errors.go eval.go expr.go exprstring.go initorder.go labels.go lookup.go methodset.go object.go objset.go operand.go ordering.go package.go predicates.go resolver.go return.go scope.go selection.go sizes.go stmt.go type.go typestring.go typexpr.go universe.go

变量

var (
        Universe *Scope
        Unsafe   *Package)
var Typ = []*Basic{
        Invalid: {Invalid, 0, "invalid type"},

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

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

func AssertableTo

func AssertableTo(V *Interface, T Type) bool

AssertableTo报告是否可以声明类型V的值具有类型T.

func AssignableTo

func AssignableTo(V, T Type) bool

AssignableTo报告类型V的值是否可分配给类型为T的变量。

func Comparable

func Comparable(T Type) bool

可比较的报告类型T的值是否可比。

func ConvertibleTo

func ConvertibleTo(V, T Type) bool

ConvertibleTo报告类型V的值是否可转换为类型T的值。

func DefPredeclaredTestFuncs

func DefPredeclaredTestFuncs()

DefPredeclaredTestFuncs定义了断言和跟踪内建。这些内置程序仅用于调试和测试此软件包。

func ExprString

func ExprString(x ast.Expr) string

ExprString返回x的(可能简化的)字符串表示。

func Id

func Id(pkg *Package, name string) string

如果导出的名称为ID,则返回名称,否则返回符合包路径的名称。

func Identical

func Identical(x, y Type) bool

相同的报告,无论x和y是否相同。

func IdenticalIgnoreTags

func IdenticalIgnoreTags(x, y Type) bool

如果标记被忽略,IdenticalIgnoreTags报告x和y是否相同。

func Implements

func Implements(V Type, T *Interface) bool

实现报告类型V是否实现接口T.

func IsInterface

func IsInterface(typ Type) bool

IsInterface报告typ是否是接口类型。

func ObjectString

func ObjectString(obj Object, qf Qualifier) string

ObjectString返回obj的字符串形式。限定符控制包级别对象的打印,可能为零。

func SelectionString

func SelectionString(s *Selection, qf Qualifier) string

SelectionString返回s的字符串形式。限定符控制包级别对象的打印,可能为零。

例子:

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

func TypeString

func TypeString(typ Type, qf Qualifier) string

TypeString返回typ的字符串表示形式。限定符控制包级别对象的打印,可能为零。

func WriteExpr

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

WriteExpr将(可能简化的)x的字符串表示写入buf。

func WriteSignature

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

WriteSignature将签名sig的表示形式写入buf,而没有前导的“func”关键字。限定符控制包级别对象的打印,可能为零。

func WriteType

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

WriteType将typ的字符串表示形式写入buf。限定符控制包级别对象的打印,可能为零。

type Array

一个Array表示一个数组类型。

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

func NewArray

func NewArray(elem Type, len int64) *Array

NewArray为给定的元素类型和长度返回一个新的数组类型。

func (*Array) Elem

func (a *Array) Elem() Type

Elem返回元素类型的数组a。

func (*Array) Len

func (a *Array) Len() int64

Len返回数组a的长度。

func (*Array) String

func (t *Array) String() string

func (*Array) Underlying

func (t *Array) Underlying() Type

type Basic

Basic代表基本类型。

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

func (*Basic) Info

func (b *Basic) Info() BasicInfo

Info返回有关基本类型b属性的信息。

func (*Basic) Kind

func (b *Basic) Kind() BasicKind

Kind返回那种基本类型b。

func (*Basic) Name

func (b *Basic) Name() string

Name返回基本类型的名称b。

func (*Basic) String

func (t *Basic) String() string

func (*Basic) Underlying

func (t *Basic) Underlying() Type

type BasicInfo

BasicInfo是一组描述基本类型属性的标志。

type BasicInfo int

基本类型的属性。

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

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

type BasicKind

BasicKind描述了这种基本类型。

type BasicKind int
const (
        Invalid BasicKind = iota // type is invalid        // predeclared types
        Bool
        Int
        Int8
        Int16
        Int32
        Int64
        Uint
        Uint8
        Uint16
        Uint32
        Uint64
        Uintptr
        Float32
        Float64
        Complex64
        Complex128
        String
        UnsafePointer        // types for untyped values
        UntypedBool
        UntypedInt
        UntypedRune
        UntypedFloat
        UntypedComplex
        UntypedString
        UntypedNil        // aliases
        Byte = Uint8
        Rune = Int32)

type Builtin

Builtin代表内置函数。Builtins没有有效的类型。

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

func (*Builtin) Exported

func (obj *Builtin) Exported() bool

func (*Builtin) Id

func (obj *Builtin) Id() string

func (*Builtin) Name

func (obj *Builtin) Name() string

func (*Builtin) Parent

func (obj *Builtin) Parent() *Scope

func (*Builtin) Pkg

func (obj *Builtin) Pkg() *Package

func (*Builtin) Pos

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

func (*Builtin) String

func (obj *Builtin) String() string

func (*Builtin) Type

func (obj *Builtin) Type() Type

type Chan

Chan代表频道类型。

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

func NewChan

func NewChan(dir ChanDir, elem Type) *Chan

NewChan为给定的方向和元素类型返回一个新的通道类型。

func (*Chan) Dir

func (c *Chan) Dir() ChanDir

Dir返回通道c的方向。

func (*Chan) Elem

func (c *Chan) Elem() Type

Elem返回通道c的元素类型。

func (*Chan) String

func (t *Chan) String() string

func (*Chan) Underlying

func (t *Chan) Underlying() Type

type ChanDir

ChanDir值表示通道方向。

type ChanDir int

通道的方向由这些常数中的一个表示。

const (
        SendRecv ChanDir = iota
        SendOnly
        RecvOnly)

type Checker

Checke维护类型检查器的状态。它必须使用NewChecker创建。

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

func NewChecker

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

NewChecker为给定的包返回一个新的Checker实例。包文件可以通过checker.Files增量添加。

func (*Checker) Files

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

Files将检查提供的文件作为检查程序包的一部分。

type Config

Config指定类型检查的配置。Config的零值是一个随时可用的默认配置。

type Config struct {        // If IgnoreFuncBodies is set, function bodies are not        // type-checked.
        IgnoreFuncBodies bool        // If FakeImportC is set, `import "C"` (for packages requiring Cgo)        // declares an empty "C" package and errors are omitted for qualified        // identifiers referring to package C (which won't find an object).        // This feature is intended for the standard library cmd/api tool.        //        // Caution: Effects may be unpredictable due to follow-on errors.        //          Do not use casually!
        FakeImportC bool        // If Error != nil, it is called with each error found        // during type checking; err has dynamic type Error.        // Secondary errors (for instance, to enumerate all types        // involved in an invalid recursive type declaration) have        // error strings that start with a '\t' character.        // If Error == nil, type-checking stops with the first        // error found.
        Error func(err error)        // An importer is used to import packages referred to from        // import declarations.        // If the installed importer implements ImporterFrom, the type        // checker calls ImportFrom instead of Import.        // The type checker reports an error if an importer is needed        // but none was installed.
        Importer Importer        // If Sizes != nil, it provides the sizing functions for package unsafe.        // Otherwise SizesFor("gc", "amd64") is used instead.
        Sizes Sizes        // If DisableUnusedImportCheck is set, packages are not checked        // for unused imports.
        DisableUnusedImportCheck bool}

func (*Config) Check

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

检查类型 - 检查包并返回结果包对象和第一个错误(如果有的话)。此外,如果info!= nil,则检查信息结构中的每个非零映射。

如果没有错误发生,软件包被标记为完成,否则它是不完整的。请参阅Config.Error以在出现错误时控制行为。

该软件包由* ast.Files和相应的文件集列表以及软件包标识的软件包路径指定。干净的路径不能为空或点(“。”)。

type Const

Const表示一个声明的常量。

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

func NewConst

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

func (*Const) Exported

func (obj *Const) Exported() bool

func (*Const) Id

func (obj *Const) Id() string

func (*Const) Name

func (obj *Const) Name() string

func (*Const) Parent

func (obj *Const) Parent() *Scope

func (*Const) Pkg

func (obj *Const) Pkg() *Package

func (*Const) Pos

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

func (*Const) String

func (obj *Const) String() string

func (*Const) Type

func (obj *Const) Type() Type

func (*Const) Val

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

type Error

Error 描述了类型检查错误; 它实现了错误接口。“软”错误是仍然允许对包进行有效解释的错误(例如“未使用的变量”); 如果忽略,“硬”错误可能会导致不可预知的行为。

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

func (Error) Error

func (err Error) Error() string

Error返回格式如下的错误字符串:filename:line:column:message

type Func

Func表示声明的函数,具体方法或抽象(接口)方法。它的Type()总是一个* Signature。由于嵌入,抽象方法可能属于许多接口。

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

func MissingMethod

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

如果V实现了T,则MissingMethod返回(nil,false),否则返回T所需的缺失方法以及它是否丢失或仅具有错误类型。

对于非接口类型V,或者如果设置了静态,V如果T中的所有方法都存在于V中,则实现T.否则(V是接口并且未设置静态),MissingMethod仅检查同时存在的T的方法在V中具有匹配类型(例如,对于类型声明x(T),其中x是接口类型V)。

func NewFunc

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

func (*Func) Exported

func (obj *Func) Exported() bool

func (*Func) FullName

func (obj *Func) FullName() string

FullName返回函数或方法obj的包或接收器类型限定名称。

func (*Func) Id

func (obj *Func) Id() string

func (*Func) Name

func (obj *Func) Name() string

func (*Func) Parent

func (obj *Func) Parent() *Scope

func (*Func) Pkg

func (obj *Func) Pkg() *Package

func (*Func) Pos

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

func (*Func) Scope

func (obj *Func) Scope() *Scope

func (*Func) String

func (obj *Func) String() string

func (*Func) Type

func (obj *Func) Type() Type

type ImportMode

ImportMode保留供将来使用。

type ImportMode int

type Importer

Importer程序解析导入到程序包的路径。

小心:此界面不支持导入本地出售的软件包。见https://golang.org/s/go15vendor。如果可能的话,外部实现应该实现ImporterFrom。

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

type ImporterFrom

一个ImporterFrom解析导入路径到包; 它支持根据https://golang.org/s/go15vendor进行销售。使用go / importer获取一个ImporterFrom实现。

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

type Info

Info包含类型检查包的结果类型信息。只收集提供地图的信息。如果软件包有类型错误,则收集的信息可能不完整。

type Info struct {        // Types maps expressions to their types, and for constant        // expressions, also their values. Invalid expressions are        // omitted.        //        // For (possibly parenthesized) identifiers denoting built-in        // functions, the recorded signatures are call-site specific:        // if the call result is not a constant, the recorded type is        // an argument-specific signature. Otherwise, the recorded type        // is invalid.        //        // The Types map does not record the type of every identifier,        // only those that appear where an arbitrary expression is        // permitted. For instance, the identifier f in a selector        // expression x.f is found only in the Selections map, the        // identifier z in a variable declaration 'var z int' is found        // only in the Defs map, and identifiers denoting packages in        // qualified identifiers are collected in the Uses map.
        Types map[ast.Expr]TypeAndValue        // 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 anonymous field, Defs returns the field *Var it defines.        //        // Invariant: Defs[id] == nil || Defs[id].Pos() == id.Pos()
        Defs map[*ast.Ident]Object        // Uses maps identifiers to the objects they denote.        //        // For an anonymous field, Uses returns the *TypeName it denotes.        //        // Invariant: Uses[id].Pos() != id.Pos()
        Uses map[*ast.Ident]Object        // Implicits maps nodes to their implicitly declared objects, if any.        // The following node and object types may appear:        //        //	node               declared object        //        //	*ast.ImportSpec    *PkgName for dot-imports and imports without renames        //	*ast.CaseClause    type-specific *Var for each type switch case clause (incl. default)        //      *ast.Field         anonymous parameter *Var        //
        Implicits map[ast.Node]Object        // Selections maps selector expressions (excluding qualified identifiers)        // to their corresponding selections.
        Selections map[*ast.SelectorExpr]*Selection        // Scopes maps ast.Nodes to the scopes they define. Package scopes are not        // associated with a specific node but with all files belonging to a package.        // Thus, the package scope can be found in the type-checked Package object.        // Scopes nest, with the Universe scope being the outermost scope, enclosing        // the package scope, which contains (one or more) files scopes, which enclose        // function scopes which in turn enclose statement and function literal scopes.        // Note that even though package-level functions are declared in the package        // scope, the function scopes are embedded in the file scope of the file        // containing the function declaration.        //        // The following node types may appear in Scopes:        //        //	*ast.File        //	*ast.FuncType        //	*ast.BlockStmt        //	*ast.IfStmt        //	*ast.SwitchStmt        //	*ast.TypeSwitchStmt        //	*ast.CaseClause        //	*ast.CommClause        //	*ast.ForStmt        //	*ast.RangeStmt        //
        Scopes map[ast.Node]*Scope        // InitOrder is the list of package-level initializers in the order in which        // they must be executed. Initializers referring to variables related by an        // initialization dependency appear in topological order, the others appear        // in source order. Variables without an initialization expression do not        // appear in this list.
        InitOrder []*Initializer}

例子

ExampleInfo在type.Info结构中显示类型检查器记录的各种事实:每个命名对象的定义和引用,以及包中每个表达式的类型,值和模式。

代码:

// 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, err := parser.ParseFile(fset, "fib.go", input, 0)if err != nil {
        log.Fatal(err)}// Type-check the package.// We create an empty map for each kind of input// we're interested in, and Check populates them.info := types.Info{
        Types: make(map[ast.Expr]types.TypeAndValue),
        Defs:  make(map[*ast.Ident]types.Object),
        Uses:  make(map[*ast.Ident]types.Object),}var conf types.Config
pkg, err := conf.Check("fib", fset, []*ast.File{f}, &info)if err != nil {
        log.Fatal(err)}// Print package-level variables in initialization order.fmt.Printf("InitOrder: %v\n\n", info.InitOrder)// For each named object, print the line and// column of its definition and each of its uses.fmt.Println("Defs and Uses of each named object:")usesByObj := make(map[types.Object][]string)for id, obj := range info.Uses {
        posn := fset.Position(id.Pos())
        lineCol := fmt.Sprintf("%d:%d", posn.Line, posn.Column)
        usesByObj[obj] = append(usesByObj[obj], lineCol)}var items []stringfor obj, uses := range usesByObj {
        sort.Strings(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)}sort.Strings(items) // sort by line:col, in effectfmt.Println(strings.Join(items, "\n"))fmt.Println()fmt.Println("Types and Values of each expression:")items = nilfor expr, tv := range info.Types {        var buf bytes.Buffer
        posn := fset.Position(expr.Pos())
        tvstr := tv.Type.String()        if tv.Value != nil {
                tvstr += " = " + tv.Value.String()        }        // line:col | expr | mode : type = value
        fmt.Fprintf(&buf, "%2d:%2d | %-19s | %-7s : %s",
                posn.Line, posn.Column, exprString(fset, expr),                mode(tv), tvstr)
        items = append(items, buf.String())}sort.Strings(items)fmt.Println(strings.Join(items, "\n"))

输出:

InitOrder: [c = "hello" b = S(c) a = len(b)]Defs and Uses of each named object:builtin len:
  defined at -
  used at 6:15func fib(x int) int:
  defined at fib.go:8:6
  used at 12:20, 12:9type S string:
  defined at fib.go:4:6
  used at 6:23type int:
  defined at -
  used at 8:12, 8:17type string:
  defined at -
  used at 4:8var b S:
  defined at fib.go:6:8
  used at 6:19var c string:
  defined at fib.go:6:11
  used at 6:25var x int:
  defined at fib.go:8:10
  used at 10:10, 12:13, 12:24, 9:5Types and Values of each expression: 4: 8 | string              | type    : string 6:15 | len                 | builtin : func(string) int 6:15 | len(b)              | value   : int 6:19 | b                   | var     : fib.S 6:23 | S                   | type    : fib.S 6:23 | S(c)                | value   : fib.S 6:25 | c                   | var     : string 6:29 | "hello"             | value   : string = "hello" 8:12 | int                 | type    : int 8:17 | int                 | type    : int 9: 5 | x                   | var     : int 9: 5 | x < 2               | value   : untyped bool 9: 9 | 2                   | value   : int = 210:10 | x                   | var     : int12: 9 | fib                 | value   : func(x int) int12: 9 | fib(x - 1)          | value   : int12: 9 | fib(x-1) - fib(x-2) | value   : int12:13 | x                   | var     : int12:13 | x - 1               | value   : int12:15 | 1                   | value   : int = 112:20 | fib                 | value   : func(x int) int12:20 | fib(x - 2)          | value   : int12:24 | x                   | var     : int12:24 | x - 2               | value   : int12:26 | 2                   | value   : int = 2

func (*Info) ObjectOf

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

ObjectOf返回由指定的id表示的对象,如果没有找到,则返回nil。

如果id是一个匿名结构字段,则ObjectOf返回它使用的字段(* Var),而不是它定义的类型(* TypeName)。

先决条件:使用和Defs地图被填充。

func (*Info) TypeOf

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

TypeOf返回表达式e的类型,如果未找到,则返回nil。先决条件:填充类型,使用和定义地图。

type Initializer

Initializer描述一个程序包级别的变量或多值初始化表达式中的变量列表,以及相应的初始化表达式。

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

func (*Initializer) String

func (init *Initializer) String() string

type Interface

Interfac表示接口类型。

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

func NewInterface

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

NewInterface为给定的方法和嵌入式类型返回一个新的接口。

func (*Interface) Complete

func (t *Interface) Complete() *Interface

Complete计算接口的方法集。必须在接口的嵌入类型完全定义之后,以及除了形成其他类型之外的任何其他方式使用接口类型之前,由NewInterface的用户调用它。Complete返回接收器。

func (*Interface) Embedded

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

嵌入返回0 <= i <t.NumEmbeddeds()的第i个嵌入类型的接口t。这些类型由相应的TypeName的唯一ID排序。

func (*Interface) Empty

func (t *Interface) Empty() bool

如果t是空的界面,则空值返回true。

func (*Interface) ExplicitMethod

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

ExplicitMethod为0 <= i <t.NumExplicitMethods()返回接口t显式声明的方法。这些方法按其唯一标识进行排序。

func (*Interface) Method

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

方法返回0 <= i <t.NumMethods()的接口t的第i个方法。这些方法按其唯一标识进行排序。

func (*Interface) NumEmbeddeds

func (t *Interface) NumEmbeddeds() int

NumEmbeddeds返回接口t中嵌入类型的数量。

func (*Interface) NumExplicitMethods

func (t *Interface) NumExplicitMethods() int

NumExplicitMethods返回接口t的显式声明方法的数量。

func (*Interface) NumMethods

func (t *Interface) NumMethods() int

NumMethods返回接口t的方法总数。

func (*Interface) String

func (t *Interface) String() string

func (*Interface) Underlying

func (t *Interface) Underlying() Type

type Label

Label 代表一个声明的标签。

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

func NewLabel

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

func (*Label) Exported

func (obj *Label) Exported() bool

func (*Label) Id

func (obj *Label) Id() string

func (*Label) Name

func (obj *Label) Name() string

func (*Label) Parent

func (obj *Label) Parent() *Scope

func (*Label) Pkg

func (obj *Label) Pkg() *Package

func (*Label) Pos

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

func (*Label) String

func (obj *Label) String() string

func (*Label) Type

func (obj *Label) Type() Type

type Map

Map代表地图类型。

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

func NewMap

func NewMap(key, elem Type) *Map

NewMap为给定的键和元素类型返回一个新的映射。

func (*Map) Elem

func (m *Map) Elem() Type

Elem返回地图m的元素类型。

func (*Map) Key

func (m *Map) Key() Type

Key返回地图m的键类型。

func (*Map) String

func (t *Map) String() string

func (*Map) Underlying

func (t *Map) Underlying() Type

type MethodSet

MethodSet是一组有序的或抽象(接口)方法的有序集合; 一个方法是一个MethodVal选择,它们按照m.Obj()。Id()的顺序排序。MethodSet的零值是一个随时可用的空方法集。

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

例子

ExampleMethodSet打印各种类型的方法集。

package mainimport ("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) }
`
	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()}}

func NewMethodSet

func NewMethodSet(T Type) *MethodSet

NewMethodSet返回为给定类型T设置的方法。它总是返回一个非零方法集,即使它是空的。

func (*MethodSet) At

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

在返回s中的第i个方法为0 <= i <s.Len()。

func (*MethodSet) Len

func (s *MethodSet) Len() int

Len返回s中方法的数量。

func (*MethodSet) Lookup

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

查找将返回匹配包和名称的方法,如果未找到,则返回nil。

func (*MethodSet) String

func (s *MethodSet) String() string

type Named

名称代表一个指定类型。

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

func NewNamed

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

NewNamed为给定的类型名称,基础类型和关联的方法返回一个新的命名类型。基础类型不能是*命名。

func (*Named) AddMethod

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

AddMethod添加方法m,除非它已经在方法列表中。TODO(gri)找到一个更好的解决方案,而不是提供这个功能

func (*Named) Method

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

方法返回0 <= i <t.NumMethods()的命名类型t的第i个方法。

func (*Named) NumMethods

func (t *Named) NumMethods() int

NumMethods返回接收者被命名为类型t的显式方法的数量。

func (*Named) Obj

func (t *Named) Obj() *TypeName

Obj返回指定类型t的类型名称。

func (*Named) SetUnderlying

func (t *Named) SetUnderlying(underlying Type)

SetUnderlying设置底层类型并将t标记为完整。TODO(gri)确定是否有更好的解决方案,而不是提供此功能

func (*Named) String

func (t *Named) String() string

func (*Named) Underlying

func (t *Named) Underlying() Type

type Nil

无表示预先声明的值nil。

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

func (*Nil) Exported

func (obj *Nil) Exported() bool

func (*Nil) Id

func (obj *Nil) Id() string

func (*Nil) Name

func (obj *Nil) Name() string

func (*Nil) Parent

func (obj *Nil) Parent() *Scope

func (*Nil) Pkg

func (obj *Nil) Pkg() *Package

func (*Nil) Pos

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

func (*Nil) String

func (obj *Nil) String() string

func (*Nil) Type

func (obj *Nil) Type() Type

type Object

一个对象描述了一个命名的语言实体,如包,常量,类型,变量,函数(包括方法)或标签。所有对象都实现了Object接口。

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

func LookupFieldOrMethod

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

LookupFieldOrMethod在T中查找具有给定包和名称的字段或方法,并返回相应的* Var或* Func,一个索引序列和一个bool,指示在字段或方法的路径上是否存在任何指针间接。如果设置了可寻址,则T是可寻址变量的类型(仅用于方法查找)。

最后一个索引条目是找到该条目的(可能是嵌入的)类型中的字段或方法索引,可以是:

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

较早的索引条目是从深度0开始,遍历到找到的条目的匿名结构字段的索引。

如果没有找到条目,则返回一个零对象。在这种情况下,返回的索引和间接值具有以下含义:

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

type Package

一个包描述了一个Go包。

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

func NewPackage

func NewPackage(path, name string) *Package

NewPackage为给定的包路径和名称返回一个新的包。该软件包不完整,不包含明确的导入。

func (*Package) Complete

func (pkg *Package) Complete() bool

如果其范围包含(至少)所有导出的对象,则该包是完整的; 否则它是不完整的。

func (*Package) Imports

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

Imports返回由pkg直接导入的包列表; 该列表按来源顺序排列。

如果pkg是从导出数据加载的,Imports包含提供pkg引用的软件包级对象的软件包。这可能比pkg的源代码直接导入的包集多或少。

func (*Package) MarkComplete

func (pkg *Package) MarkComplete()

MarkComplete将包标记为完整。

func (*Package) Name

func (pkg *Package) Name() string

名称返回包名称。

func (*Package) Path

func (pkg *Package) Path() string

Path返回包路径。

func (*Package) Scope

func (pkg *Package) Scope() *Scope

Scope返回包含在包级别声明的对象(TypeNames,Consts,Vars和Funcs)的(完整或不完整)包范围。

func (*Package) SetImports

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

SetImports将显式导入的软件包列表设置为列表。确保列表元素是唯一的是调用者的责任。

func (*Package) SetName

func (pkg *Package) SetName(name string)

SetName设置包名称。

func (*Package) String

func (pkg *Package) String() string

type PkgName

PkgName代表一个导入的Go包。

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

func NewPkgName

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

func (*PkgName) Exported

func (obj *PkgName) Exported() bool

func (*PkgName) Id

func (obj *PkgName) Id() string

func (*PkgName) Imported

func (obj *PkgName) Imported() *Package

Imported 返回已导入的包。它与Pkg()不同,后者是包含import语句的包。

func (*PkgName) Name

func (obj *PkgName) Name() string

func (*PkgName) Parent

func (obj *PkgName) Parent() *Scope

func (*PkgName) Pkg

func (obj *PkgName) Pkg() *Package

func (*PkgName) Pos

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

func (*PkgName) String

func (obj *PkgName) String() string

func (*PkgName) Type

func (obj *PkgName) Type() Type

type Pointer

Pointer 表示指针类型。

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

func NewPointer

func NewPointer(elem Type) *Pointer

NewPointer为给定的元素(基)类型返回一个新的指针类型。

func (*Pointer) Elem

func (p *Pointer) Elem() Type

Elem返回给定指针p的元素类型。

func (*Pointer) String

func (t *Pointer) String() string

func (*Pointer) Underlying

func (t *Pointer) Underlying() Type

type Qualifier

Qualifier控制如何在对TypeString,ObjectString和SelectionString的调用中打印指定的包级对象。

这三个格式化例程为每个包级别对象O调用限定符,如果限定符返回非空字符串p,则该对象将以pO形式打印。如果它返回空字符串,则仅打印对象名称O.

使用无限定符相当于使用(* Package).Path:该对象由导入路径限定,例如“encoding / json.Marshal”。

type Qualifier func(*Package) string

func RelativeTo

func RelativeTo(pkg *Package) Qualifier

RelativeTo(pkg)返回一个限定符,它可以完全限定除pkg以外的所有包的成员。

type Scope

范围维护一组对象和指向其包含(父)和包含(子)范围的链接。对象可以插入并按名称查找。范围的零值是一个随时可用的空范围。

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

例子

ExampleScope打印从一组解析文件创建的包的范围树。

package mainimport ("bytes""fmt""go/ast""go/importer""go/parser""go/token""go/types""log""regexp")func main() {// Parse the source files for a package.
	fset := token.NewFileSet()var files []*ast.Filefor _, file := range []struct{ name, input string }{{"main.go", `
package main
import "fmt"
func main() {
	freezing := FToC(-18)
	fmt.Println(freezing, Boiling) }
`},{"celsius.go", `
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
`},} {
		f, err := parser.ParseFile(fset, file.name, file.input, 0)if err != nil {
			log.Fatal(err)}
		files = append(files, f)}// Type-check a package consisting of these files.// Type information for the imported "fmt" package// comes from $GOROOT/pkg/$GOOS_$GOOARCH/fmt.a.
	conf := types.Config{Importer: importer.Default()}
	pkg, err := conf.Check("temperature", fset, files, nil)if err != nil {
		log.Fatal(err)}// Print the tree of scopes.// For determinism, we redact addresses.var buf bytes.Buffer
	pkg.Scope().WriteTo(&buf, 0, true)
	rx := regexp.MustCompile(` 0x[a-fA-F0-9]*`)
	fmt.Println(rx.ReplaceAllString(buf.String(), ""))}

func NewScope

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

如果有的话,NewScope返回给定父范围中包含的新的空范围。该评论仅用于调试。

func (*Scope) Child

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

Child返回第i个子范围为0 <= i <NumChildren()。

func (*Scope) Contains

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

如果pos在范围的范围内,则Contains返回true。只有类型检查的AST具有完整的位置信息,结果才能保证有效。

func (*Scope) End

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

func (*Scope) Innermost

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

Innermost返回包含pos的最内层(子)范围。如果pos不在任何范围内,结果为零。宇宙范围的结果也是零。只有类型检查的AST具有完整的位置信息,结果才能保证有效。

func (*Scope) Insert

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

插入尝试将对象obj插入到作用域s中。如果s已经包含一个具有相同名称的替代对象alt,则Insert将保持不变并返回alt。否则,它插入obj,设置对象的父级作用域(如果尚未设置),并返回nil。

func (*Scope) Len

func (s *Scope) Len() int

Len()返回范围元素的数量。

func (*Scope) Lookup

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

如果这样的对象存在,Lookup将返回给定名称的范围s中的对象; 否则结果为零。

func (*Scope) LookupParent

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

LookupParent遵循以s开头的作用域的父链,直到找到一个作用域,其中Lookup(name)返回一个非零对象,然后返回该作用域和对象。如果提供有效位置pos,则只考虑在pos或之前声明的对象。如果不存在这样的范围和对象,则结果是(无,无)。

请注意,如果对象被插入到作用域中并且此时已经有父对象(请参阅下面的插入),则obj.Parent()可能与返回的作用域不同。这仅适用于点导入的对象,其范围是导出它们的包的范围。

func (*Scope) Names

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

Names 按排序顺序返回作用域的元素名称。

func (*Scope) NumChildren

func (s *Scope) NumChildren() int

NumChildren()返回嵌套在s中的范围数。

func (*Scope) Parent

func (s *Scope) Parent() *Scope

Parent返回范围的包含(父)范围。

func (*Scope) Pos

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

Pos和End描述范围的源代码范围[pos,end)。只有类型检查的AST具有完整的位置信息,结果才能保证有效。Universe和程序包作用域的范围未定义。

func (*Scope) String

func (s *Scope) String() string

字符串返回范围的字符串表示形式,用于调试。

func (*Scope) WriteTo

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

WriteTo将范围的字符串表示形式写入w,范围元素按名称排序。缩进级别由n> = 0控制,n == 0表示无缩进。如果设置了递归,它还会写入嵌套(子)范围。

type Selection

Selection述了一个选择器表达式xf对于声明:

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

存在以下关系:

Selector    Kind          Recv    Obj    Type               Index     Indirect

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

func (*Selection) Index

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

索引描述xf中从x到f的路径最后一个索引条目是声明f的类型的字段或方法索引; 之一:

1) the list of declared methods of a named type; or2) the list of methods of an interface type; or3) the list of fields of a struct type.

较早的索引条目是从嵌入深度0开始隐式遍历以从(类型)x到f得到的嵌入字段的索引。

func (*Selection) Indirect

func (s *Selection) Indirect() bool

Indirect报告是否需要在xf中从x到f得到任何指针间接

func (*Selection) Kind

func (s *Selection) Kind() SelectionKind

Kind返回选择类。

func (*Selection) Obj

func (s *Selection) Obj() Object

Obj返回由xf表示的对象; 在所有其他情况下,用于字段选择的a * Var以及* Func。

func (*Selection) Recv

func (s *Selection) Recv() Type

Recv返回xf中x的类型

func (*Selection) String

func (s *Selection) String() string

func (*Selection) Type

func (s *Selection) Type() Type

Type返回xf的类型,这可能与f的类型不同。请参阅选择了解更多信息。

type SelectionKind

SelectionKind描述了选择器表达式xf的类型(不包括限定标识符)。

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

type Signature

Signature代表(非内建)函数或方法类型。

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

func NewSignature

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

NewSignature为给定的接收器,参数和结果返回一个新的函数类型,其中任何一个都可以为零。如果设置了可变参数,则该函数是可变参数,它必须至少有一个参数,最后一个参数必须是未命名的片类型。

func (*Signature) Params

func (s *Signature) Params() *Tuple

Params返回签名s的参数,或者nil。

func (*Signature) Recv

func (s *Signature) Recv() *Var

Recv返回签名s的接收者(如果是方法),否则返回nil。

对于抽象方法,Recv将封闭接口作为* Named或* Interface返回。由于嵌入,接口可能包含其接收器类型是不同接口的方法。

func (*Signature) Results

func (s *Signature) Results() *Tuple

Results返回签名的结果,或零。

func (*Signature) String

func (t *Signature) String() string

func (*Signature) Underlying

func (t *Signature) Underlying() Type

func (*Signature) Variadic

func (s *Signature) Variadic() bool

Variadic报告签名是否是可变的。

type Sizes

Sizes定义了封装不安全的尺寸函数。

type Sizes interface {        // Alignof returns the alignment of a variable of type T.        // Alignof must implement the alignment guarantees required by the spec.        Alignof(T Type) int64        // Offsetsof returns the offsets of the given struct fields, in bytes.        // Offsetsof must implement the offset guarantees required by the spec.        Offsetsof(fields []*Var) []int64        // Sizeof returns the size of a variable of type T.        // Sizeof must implement the size guarantees required by the spec.        Sizeof(T Type) int64}

func SizesFor

func SizesFor(compiler, arch string) Sizes

SizesFor返回编译器用于体系结构的大小。如果编译器/体系结构对未知,结果为零。

编译器“gc”支持的体系结构:“386”,“arm”,“arm64”,“amd64”,“amd64p32”,“mips”,“mipsle”,“mips64”,“mips64le”,“ppc64”,“ppc64le “,”s390x“。

type Slice

切片表示切片类型。

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

func NewSlice

func NewSlice(elem Type) *Slice

NewSlice为给定的元素类型返回一个新的切片类型。

func (*Slice) Elem

func (s *Slice) Elem() Type

Elem返回切片的元素类型。

func (*Slice) String

func (t *Slice) String() string

func (*Slice) Underlying

func (t *Slice) Underlying() Type

type StdSizes

StdSizes是创建常用大小的便利类型。它做出以下简化假设:

- 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实现大小。

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

func (*StdSizes) Alignof

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

func (*StdSizes) Offsetsof

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

func (*StdSizes) Sizeof

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

type Struct

一个Struct表示一个结构类型。

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

func NewStruct

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

NewStruct返回一个带有给定字段和相应字段标签的新结构。如果索引为i的字段有一个标签,则tagsi必须是该标签,但len(标签)可能只有在索引i最大时才需要。因此,如果没有字段有标签,标签可能为零。

func (*Struct) Field

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

Field返回第i个字段0 <= i <NumFields()。

func (*Struct) NumFields

func (s *Struct) NumFields() int

NumFields返回结构中字段的数量(包括空白字段和匿名字段)。

func (*Struct) String

func (t *Struct) String() string

func (*Struct) Tag

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

标记为0 <= i <NumFields()返回第i个字段标记。

func (*Struct) Underlying

func (t *Struct) Underlying() Type

type Tuple

一个Tuple表示一个有序的变量列表; 一个零*元组是一个有效的(空)元组。元组被用作签名的组成部分并表示多个赋值的类型; 他们不是Go的头等类型。

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

func NewTuple

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

NewTuple为给定的变量返回一个新的元组。

func (*Tuple) At

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

At返回元组t的第i个变量。

func (*Tuple) Len

func (t *Tuple) Len() int

Len返回元组t的数字变量。

func (*Tuple) String

func (t *Tuple) String() string

func (*Tuple) Underlying

func (t *Tuple) Underlying() Type

type Type

Type代表一种Go。所有类型都实现了Type接口。

type Type interface {        // Underlying returns the underlying type of a type.        Underlying() Type        // String returns a string representation of a type.        String() string}

func Default

func Default(typ Type) Type

Default返回“无类型”类型的默认“类型”类型; 它返回所有其他类型的传入类型。untyped nil的默认类型是无类型nil。

type TypeAndValue

TypeAndValue报告相应表达式的类型和值(对于常量)。

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

func Eval

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

Eval返回类型,如果常量,则返回表达式expr的值,在包pkg的位置pos处计算,该值必须是从类型检查AST检查AST并提供相对于提供的文件集的完整位置信息。

如果表达式包含函数文字,则忽略它们的正文(即,未对文体进行类型检查)。

如果pkg == nil,则使用Universe范围,并忽略所提供的位置pos。如果pkg!= nil且pos无效,则使用软件包范围。否则,pos必须属于包。

如果pos不在包内或者无法评估节点,则会返回错误。

注意:不应该使用Eval来代替运行Check来计算类型和值,但除了Check之外。Eval每次都会重新评估它的参数,它也不知道使用表达式的上下文(例如,赋值)。因此,顶层的无类型常量将返回一个无类型的类型,而不是相应的特定于上下文的类型。

func (TypeAndValue) Addressable

func (tv TypeAndValue) Addressable() bool

Addressable报告相应的表达式是否可寻址(https://golang.org/ref/spec#Address_operators)。

func (TypeAndValue) Assignable

func (tv TypeAndValue) Assignable() bool

Assignable报告相应的表达式是否可分配给(提供正确类型的值)。

func (TypeAndValue) HasOk

func (tv TypeAndValue) HasOk() bool

HasOk报告相应的表达式是否可用于逗号分配的lhs。

func (TypeAndValue) IsBuiltin

func (tv TypeAndValue) IsBuiltin() bool

IsBuiltin报告相应的表达式是否表示一个(可能括号内的)内置函数。

func (TypeAndValue) IsNil

func (tv TypeAndValue) IsNil() bool

IsNil报告相应的表达式是否表示预先声明的值nil。

func (TypeAndValue) IsType

func (tv TypeAndValue) IsType() bool

IsType报告相应的表达式是否指定一个类型。

func (TypeAndValue) IsValue

func (tv TypeAndValue) IsValue() bool

IsValue报告相应的表达式是否为值。建筑物不被视为价值。常量值具有非零值。

func (TypeAndValue) IsVoid

func (tv TypeAndValue) IsVoid() bool

IsVoid报告相应的表达式是否是没有结果的函数调用。

type TypeName

TypeName表示(named或alias)类型的名称。

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

func NewTypeName

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

func (*TypeName) Exported

func (obj *TypeName) Exported() bool

func (*TypeName) Id

func (obj *TypeName) Id() string

func (*TypeName) IsAlias

func (obj *TypeName) IsAlias() bool

IsAlias报告obj是否是某个类型的别名。

func (*TypeName) Name

func (obj *TypeName) Name() string

func (*TypeName) Parent

func (obj *TypeName) Parent() *Scope

func (*TypeName) Pkg

func (obj *TypeName) Pkg() *Package

func (*TypeName) Pos

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

func (*TypeName) String

func (obj *TypeName) String() string

func (*TypeName) Type

func (obj *TypeName) Type() Type

type Var

Variable表示声明的变量(包括函数参数和结果以及结构体字段)。

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

func NewField

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

func NewParam

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

func NewVar

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

func (*Var) Anonymous

func (obj *Var) Anonymous() bool

func (*Var) Exported

func (obj *Var) Exported() bool

func (*Var) Id

func (obj *Var) Id() string

func (*Var) IsField

func (obj *Var) IsField() bool

func (*Var) Name

func (obj *Var) Name() string

func (*Var) Parent

func (obj *Var) Parent() *Scope

func (*Var) Pkg

func (obj *Var) Pkg() *Package

func (*Var) Pos

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

func (*Var) String

func (obj *Var) String() string

func (*Var) Type

func (obj *Var) Type() Type
上一篇: 下一篇: