?
本文檔使用 php中文網(wǎng)手冊 發(fā)布
import "go/types"
Overview
Index
Examples
包類型聲明數(shù)據(jù)類型并實現(xiàn)Go包的類型檢查算法。使用Config.Check來調(diào)用包的類型檢查器?;蛘?,使用NewChecker創(chuàng)建一個新的類型檢查器,并通過調(diào)用Checker.Files來遞增調(diào)用它。
類型檢查由幾個相互依賴的階段組成:
名稱解析將程序中的每個標識符(ast.Ident)映射到它表示的語言對象(Object)。使用Info。{Defs,Uses,Implicits}來獲得名稱解析的結(jié)果。
常量折疊計算每個表達式(ast.Expr)的精確常量值(constant.Value),這是一個編譯時常量。使用Info.Typesexpr.Value獲取常量折疊的結(jié)果。
類型推斷計算每個表達式(ast.Expr)的類型(Type)并檢查是否符合語言規(guī)范。使用Info.Typesexpr.Type作為類型推斷的結(jié)果。
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(V *Interface, T Type) bool
AssertableTo報告是否可以聲明類型V的值具有類型T.
func AssignableTo(V, T Type) bool
AssignableTo報告類型V的值是否可分配給類型為T的變量。
func Comparable(T Type) bool
可比較的報告類型T的值是否可比。
func ConvertibleTo(V, T Type) bool
ConvertibleTo報告類型V的值是否可轉(zhuǎn)換為類型T的值。
func DefPredeclaredTestFuncs()
DefPredeclaredTestFuncs定義了斷言和跟蹤內(nèi)建。這些內(nèi)置程序僅用于調(diào)試和測試此軟件包。
func ExprString(x ast.Expr) string
ExprString返回x的(可能簡化的)字符串表示。
func Id(pkg *Package, name string) string
如果導(dǎo)出的名稱為ID,則返回名稱,否則返回符合包路徑的名稱。
func Identical(x, y Type) bool
相同的報告,無論x和y是否相同。
func IdenticalIgnoreTags(x, y Type) bool
如果標記被忽略,IdenticalIgnoreTags報告x和y是否相同。
func Implements(V Type, T *Interface) bool
實現(xiàn)報告類型V是否實現(xiàn)接口T.
func IsInterface(typ Type) bool
IsInterface報告typ是否是接口類型。
func ObjectString(obj Object, qf Qualifier) string
ObjectString返回obj的字符串形式。限定符控制包級別對象的打印,可能為零。
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(typ Type, qf Qualifier) string
TypeString返回typ的字符串表示形式。限定符控制包級別對象的打印,可能為零。
func WriteExpr(buf *bytes.Buffer, x ast.Expr)
WriteExpr將(可能簡化的)x的字符串表示寫入buf。
func WriteSignature(buf *bytes.Buffer, sig *Signature, qf Qualifier)
WriteSignature將簽名sig的表示形式寫入buf,而沒有前導(dǎo)的“func”關(guān)鍵字。限定符控制包級別對象的打印,可能為零。
func WriteType(buf *bytes.Buffer, typ Type, qf Qualifier)
WriteType將typ的字符串表示形式寫入buf。限定符控制包級別對象的打印,可能為零。
一個Array表示一個數(shù)組類型。
type Array struct { // contains filtered or unexported fields}
func NewArray(elem Type, len int64) *Array
NewArray為給定的元素類型和長度返回一個新的數(shù)組類型。
func (a *Array) Elem() Type
Elem返回元素類型的數(shù)組a。
func (a *Array) Len() int64
Len返回數(shù)組a的長度。
func (t *Array) String() string
func (t *Array) Underlying() Type
Basic代表基本類型。
type Basic struct { // contains filtered or unexported fields}
func (b *Basic) Info() BasicInfo
Info返回有關(guān)基本類型b屬性的信息。
func (b *Basic) Kind() BasicKind
Kind返回那種基本類型b。
func (b *Basic) Name() string
Name返回基本類型的名稱b。
func (t *Basic) String() string
func (t *Basic) Underlying() Type
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)
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)
Builtin代表內(nèi)置函數(shù)。Builtins沒有有效的類型。
type Builtin struct { // contains filtered or unexported fields}
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
Chan代表頻道類型。
type Chan struct { // contains filtered or unexported fields}
func NewChan(dir ChanDir, elem Type) *Chan
NewChan為給定的方向和元素類型返回一個新的通道類型。
func (c *Chan) Dir() ChanDir
Dir返回通道c的方向。
func (c *Chan) Elem() Type
Elem返回通道c的元素類型。
func (t *Chan) String() string
func (t *Chan) Underlying() Type
ChanDir值表示通道方向。
type ChanDir int
通道的方向由這些常數(shù)中的一個表示。
const ( SendRecv ChanDir = iota SendOnly RecvOnly)
Checke維護類型檢查器的狀態(tài)。它必須使用NewChecker創(chuàng)建。
type Checker struct { *Info // contains filtered or unexported fields}
func NewChecker(conf *Config, fset *token.FileSet, pkg *Package, info *Info) *Checker
NewChecker為給定的包返回一個新的Checker實例。包文件可以通過checker.Files增量添加。
func (check *Checker) Files(files []*ast.File) error
Files將檢查提供的文件作為檢查程序包的一部分。
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 (conf *Config) Check(path string, fset *token.FileSet, files []*ast.File, info *Info) (*Package, error)
檢查類型 - 檢查包并返回結(jié)果包對象和第一個錯誤(如果有的話)。此外,如果info!= nil,則檢查信息結(jié)構(gòu)中的每個非零映射。
如果沒有錯誤發(fā)生,軟件包被標記為完成,否則它是不完整的。請參閱Config.Error以在出現(xiàn)錯誤時控制行為。
該軟件包由* ast.Files和相應(yīng)的文件集列表以及軟件包標識的軟件包路徑指定。干凈的路徑不能為空或點(“?!保?。
Const表示一個聲明的常量。
type Const struct { // contains filtered or unexported fields}
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
Error 描述了類型檢查錯誤; 它實現(xiàn)了錯誤接口。“軟”錯誤是仍然允許對包進行有效解釋的錯誤(例如“未使用的變量”); 如果忽略,“硬”錯誤可能會導(dǎo)致不可預(yù)知的行為。
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 (err Error) Error() string
Error返回格式如下的錯誤字符串:filename:line:column:message
Func表示聲明的函數(shù),具體方法或抽象(接口)方法。它的Type()總是一個* Signature。由于嵌入,抽象方法可能屬于許多接口。
type Func struct { // contains filtered or unexported fields}
func MissingMethod(V Type, T *Interface, static bool) (method *Func, wrongType bool)
如果V實現(xiàn)了T,則MissingMethod返回(nil,false),否則返回T所需的缺失方法以及它是否丟失或僅具有錯誤類型。
對于非接口類型V,或者如果設(shè)置了靜態(tài),V如果T中的所有方法都存在于V中,則實現(xiàn)T.否則(V是接口并且未設(shè)置靜態(tài)),MissingMethod僅檢查同時存在的T的方法在V中具有匹配類型(例如,對于類型聲明x(T),其中x是接口類型V)。
func NewFunc(pos token.Pos, pkg *Package, name string, sig *Signature) *Func
func (obj *Func) Exported() bool
func (obj *Func) FullName() string
FullName返回函數(shù)或方法obj的包或接收器類型限定名稱。
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
ImportMode保留供將來使用。
type ImportMode int
Importer程序解析導(dǎo)入到程序包的路徑。
小心:此界面不支持導(dǎo)入本地出售的軟件包。見https://golang.org/s/go15vendor。如果可能的話,外部實現(xiàn)應(yīng)該實現(xiàn)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)}
一個ImporterFrom解析導(dǎo)入路徑到包; 它支持根據(jù)https://golang.org/s/go15vendor進行銷售。使用go / importer獲取一個ImporterFrom實現(xiàn)。
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)}
Info包含類型檢查包的結(jié)果類型信息。只收集提供地圖的信息。如果軟件包有類型錯誤,則收集的信息可能不完整。
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結(jié)構(gòu)中顯示類型檢查器記錄的各種事實:每個命名對象的定義和引用,以及包中每個表達式的類型,值和模式。
代碼:
// 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 *Info) ObjectOf(id *ast.Ident) Object
ObjectOf返回由指定的id表示的對象,如果沒有找到,則返回nil。
如果id是一個匿名結(jié)構(gòu)字段,則ObjectOf返回它使用的字段(* Var),而不是它定義的類型(* TypeName)。
先決條件:使用和Defs地圖被填充。
func (info *Info) TypeOf(e ast.Expr) Type
TypeOf返回表達式e的類型,如果未找到,則返回nil。先決條件:填充類型,使用和定義地圖。
Initializer描述一個程序包級別的變量或多值初始化表達式中的變量列表,以及相應(yīng)的初始化表達式。
type Initializer struct { Lhs []*Var // var Lhs = Rhs Rhs ast.Expr}
func (init *Initializer) String() string
Interfac表示接口類型。
type Interface struct { // contains filtered or unexported fields}
func NewInterface(methods []*Func, embeddeds []*Named) *Interface
NewInterface為給定的方法和嵌入式類型返回一個新的接口。
func (t *Interface) Complete() *Interface
Complete計算接口的方法集。必須在接口的嵌入類型完全定義之后,以及除了形成其他類型之外的任何其他方式使用接口類型之前,由NewInterface的用戶調(diào)用它。Complete返回接收器。
func (t *Interface) Embedded(i int) *Named
嵌入返回0 <= i <t.NumEmbeddeds()的第i個嵌入類型的接口t。這些類型由相應(yīng)的TypeName的唯一ID排序。
func (t *Interface) Empty() bool
如果t是空的界面,則空值返回true。
func (t *Interface) ExplicitMethod(i int) *Func
ExplicitMethod為0 <= i <t.NumExplicitMethods()返回接口t顯式聲明的方法。這些方法按其唯一標識進行排序。
func (t *Interface) Method(i int) *Func
方法返回0 <= i <t.NumMethods()的接口t的第i個方法。這些方法按其唯一標識進行排序。
func (t *Interface) NumEmbeddeds() int
NumEmbeddeds返回接口t中嵌入類型的數(shù)量。
func (t *Interface) NumExplicitMethods() int
NumExplicitMethods返回接口t的顯式聲明方法的數(shù)量。
func (t *Interface) NumMethods() int
NumMethods返回接口t的方法總數(shù)。
func (t *Interface) String() string
func (t *Interface) Underlying() Type
Label 代表一個聲明的標簽。
type Label struct { // contains filtered or unexported fields}
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
Map代表地圖類型。
type Map struct { // contains filtered or unexported fields}
func NewMap(key, elem Type) *Map
NewMap為給定的鍵和元素類型返回一個新的映射。
func (m *Map) Elem() Type
Elem返回地圖m的元素類型。
func (m *Map) Key() Type
Key返回地圖m的鍵類型。
func (t *Map) String() string
func (t *Map) Underlying() Type
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(T Type) *MethodSet
NewMethodSet返回為給定類型T設(shè)置的方法。它總是返回一個非零方法集,即使它是空的。
func (s *MethodSet) At(i int) *Selection
在返回s中的第i個方法為0 <= i <s.Len()。
func (s *MethodSet) Len() int
Len返回s中方法的數(shù)量。
func (s *MethodSet) Lookup(pkg *Package, name string) *Selection
查找將返回匹配包和名稱的方法,如果未找到,則返回nil。
func (s *MethodSet) String() string
名稱代表一個指定類型。
type Named struct { // contains filtered or unexported fields}
func NewNamed(obj *TypeName, underlying Type, methods []*Func) *Named
NewNamed為給定的類型名稱,基礎(chǔ)類型和關(guān)聯(lián)的方法返回一個新的命名類型。基礎(chǔ)類型不能是*命名。
func (t *Named) AddMethod(m *Func)
AddMethod添加方法m,除非它已經(jīng)在方法列表中。TODO(gri)找到一個更好的解決方案,而不是提供這個功能
func (t *Named) Method(i int) *Func
方法返回0 <= i <t.NumMethods()的命名類型t的第i個方法。
func (t *Named) NumMethods() int
NumMethods返回接收者被命名為類型t的顯式方法的數(shù)量。
func (t *Named) Obj() *TypeName
Obj返回指定類型t的類型名稱。
func (t *Named) SetUnderlying(underlying Type)
SetUnderlying設(shè)置底層類型并將t標記為完整。TODO(gri)確定是否有更好的解決方案,而不是提供此功能
func (t *Named) String() string
func (t *Named) Underlying() Type
無表示預(yù)先聲明的值nil。
type Nil struct { // contains filtered or unexported fields}
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
一個對象描述了一個命名的語言實體,如包,常量,類型,變量,函數(shù)(包括方法)或標簽。所有對象都實現(xiàn)了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(T Type, addressable bool, pkg *Package, name string) (obj Object, index []int, indirect bool)
LookupFieldOrMethod在T中查找具有給定包和名稱的字段或方法,并返回相應(yīng)的* Var或* Func,一個索引序列和一個bool,指示在字段或方法的路徑上是否存在任何指針間接。如果設(shè)置了可尋址,則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開始,遍歷到找到的條目的匿名結(jié)構(gòu)字段的索引。
如果沒有找到條目,則返回一個零對象。在這種情況下,返回的索引和間接值具有以下含義:
- 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.
一個包描述了一個Go包。
type Package struct { // contains filtered or unexported fields}
func NewPackage(path, name string) *Package
NewPackage為給定的包路徑和名稱返回一個新的包。該軟件包不完整,不包含明確的導(dǎo)入。
func (pkg *Package) Complete() bool
如果其范圍包含(至少)所有導(dǎo)出的對象,則該包是完整的; 否則它是不完整的。
func (pkg *Package) Imports() []*Package
Imports返回由pkg直接導(dǎo)入的包列表; 該列表按來源順序排列。
如果pkg是從導(dǎo)出數(shù)據(jù)加載的,Imports包含提供pkg引用的軟件包級對象的軟件包。這可能比pkg的源代碼直接導(dǎo)入的包集多或少。
func (pkg *Package) MarkComplete()
MarkComplete將包標記為完整。
func (pkg *Package) Name() string
名稱返回包名稱。
func (pkg *Package) Path() string
Path返回包路徑。
func (pkg *Package) Scope() *Scope
Scope返回包含在包級別聲明的對象(TypeNames,Consts,Vars和Funcs)的(完整或不完整)包范圍。
func (pkg *Package) SetImports(list []*Package)
SetImports將顯式導(dǎo)入的軟件包列表設(shè)置為列表。確保列表元素是唯一的是調(diào)用者的責(zé)任。
func (pkg *Package) SetName(name string)
SetName設(shè)置包名稱。
func (pkg *Package) String() string
PkgName代表一個導(dǎo)入的Go包。
type PkgName struct { // contains filtered or unexported fields}
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
Imported 返回已導(dǎo)入的包。它與Pkg()不同,后者是包含import語句的包。
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
Pointer 表示指針類型。
type Pointer struct { // contains filtered or unexported fields}
func NewPointer(elem Type) *Pointer
NewPointer為給定的元素(基)類型返回一個新的指針類型。
func (p *Pointer) Elem() Type
Elem返回給定指針p的元素類型。
func (t *Pointer) String() string
func (t *Pointer) Underlying() Type
Qualifier控制如何在對TypeString,ObjectString和SelectionString的調(diào)用中打印指定的包級對象。
這三個格式化例程為每個包級別對象O調(diào)用限定符,如果限定符返回非空字符串p,則該對象將以pO形式打印。如果它返回空字符串,則僅打印對象名稱O.
使用無限定符相當于使用(* Package).Path:該對象由導(dǎo)入路徑限定,例如“encoding / json.Marshal”。
type Qualifier func(*Package) string
func RelativeTo(pkg *Package) Qualifier
RelativeTo(pkg)返回一個限定符,它可以完全限定除pkg以外的所有包的成員。
范圍維護一組對象和指向其包含(父)和包含(子)范圍的鏈接。對象可以插入并按名稱查找。范圍的零值是一個隨時可用的空范圍。
type Scope struct { // contains filtered or unexported fields}
ExampleScope打印從一組解析文件創(chuàng)建的包的范圍樹。
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(parent *Scope, pos, end token.Pos, comment string) *Scope
如果有的話,NewScope返回給定父范圍中包含的新的空范圍。該評論僅用于調(diào)試。
func (s *Scope) Child(i int) *Scope
Child返回第i個子范圍為0 <= i <NumChildren()。
func (s *Scope) Contains(pos token.Pos) bool
如果pos在范圍的范圍內(nèi),則Contains返回true。只有類型檢查的AST具有完整的位置信息,結(jié)果才能保證有效。
func (s *Scope) End() token.Pos
func (s *Scope) Innermost(pos token.Pos) *Scope
Innermost返回包含pos的最內(nèi)層(子)范圍。如果pos不在任何范圍內(nèi),結(jié)果為零。宇宙范圍的結(jié)果也是零。只有類型檢查的AST具有完整的位置信息,結(jié)果才能保證有效。
func (s *Scope) Insert(obj Object) Object
插入嘗試將對象obj插入到作用域s中。如果s已經(jīng)包含一個具有相同名稱的替代對象alt,則Insert將保持不變并返回alt。否則,它插入obj,設(shè)置對象的父級作用域(如果尚未設(shè)置),并返回nil。
func (s *Scope) Len() int
Len()返回范圍元素的數(shù)量。
func (s *Scope) Lookup(name string) Object
如果這樣的對象存在,Lookup將返回給定名稱的范圍s中的對象; 否則結(jié)果為零。
func (s *Scope) LookupParent(name string, pos token.Pos) (*Scope, Object)
LookupParent遵循以s開頭的作用域的父鏈,直到找到一個作用域,其中Lookup(name)返回一個非零對象,然后返回該作用域和對象。如果提供有效位置pos,則只考慮在pos或之前聲明的對象。如果不存在這樣的范圍和對象,則結(jié)果是(無,無)。
請注意,如果對象被插入到作用域中并且此時已經(jīng)有父對象(請參閱下面的插入),則obj.Parent()可能與返回的作用域不同。這僅適用于點導(dǎo)入的對象,其范圍是導(dǎo)出它們的包的范圍。
func (s *Scope) Names() []string
Names 按排序順序返回作用域的元素名稱。
func (s *Scope) NumChildren() int
NumChildren()返回嵌套在s中的范圍數(shù)。
func (s *Scope) Parent() *Scope
Parent返回范圍的包含(父)范圍。
func (s *Scope) Pos() token.Pos
Pos和End描述范圍的源代碼范圍[pos,end)。只有類型檢查的AST具有完整的位置信息,結(jié)果才能保證有效。Universe和程序包作用域的范圍未定義。
func (s *Scope) String() string
字符串返回范圍的字符串表示形式,用于調(diào)試。
func (s *Scope) WriteTo(w io.Writer, n int, recurse bool)
WriteTo將范圍的字符串表示形式寫入w,范圍元素按名稱排序??s進級別由n> = 0控制,n == 0表示無縮進。如果設(shè)置了遞歸,它還會寫入嵌套(子)范圍。
Selection述了一個選擇器表達式xf對于聲明:
type T struct{ x int; E }type E struct{}func (e E) m() {}var p *T
存在以下關(guān)系:
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 (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 (s *Selection) Indirect() bool
Indirect報告是否需要在xf中從x到f得到任何指針間接
func (s *Selection) Kind() SelectionKind
Kind返回選擇類。
func (s *Selection) Obj() Object
Obj返回由xf表示的對象; 在所有其他情況下,用于字段選擇的a * Var以及* Func。
func (s *Selection) Recv() Type
Recv返回xf中x的類型
func (s *Selection) String() string
func (s *Selection) Type() Type
Type返回xf的類型,這可能與f的類型不同。請參閱選擇了解更多信息。
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)
Signature代表(非內(nèi)建)函數(shù)或方法類型。
type Signature struct { // contains filtered or unexported fields}
func NewSignature(recv *Var, params, results *Tuple, variadic bool) *Signature
NewSignature為給定的接收器,參數(shù)和結(jié)果返回一個新的函數(shù)類型,其中任何一個都可以為零。如果設(shè)置了可變參數(shù),則該函數(shù)是可變參數(shù),它必須至少有一個參數(shù),最后一個參數(shù)必須是未命名的片類型。
func (s *Signature) Params() *Tuple
Params返回簽名s的參數(shù),或者nil。
func (s *Signature) Recv() *Var
Recv返回簽名s的接收者(如果是方法),否則返回nil。
對于抽象方法,Recv將封閉接口作為* Named或* Interface返回。由于嵌入,接口可能包含其接收器類型是不同接口的方法。
func (s *Signature) Results() *Tuple
Results返回簽名的結(jié)果,或零。
func (t *Signature) String() string
func (t *Signature) Underlying() Type
func (s *Signature) Variadic() bool
Variadic報告簽名是否是可變的。
Sizes定義了封裝不安全的尺寸函數(shù)。
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(compiler, arch string) Sizes
SizesFor返回編譯器用于體系結(jié)構(gòu)的大小。如果編譯器/體系結(jié)構(gòu)對未知,結(jié)果為零。
編譯器“gc”支持的體系結(jié)構(gòu):“386”,“arm”,“arm64”,“amd64”,“amd64p32”,“mips”,“mipsle”,“mips64”,“mips64le”,“ppc64”,“ppc64le “,”s390x“。
切片表示切片類型。
type Slice struct { // contains filtered or unexported fields}
func NewSlice(elem Type) *Slice
NewSlice為給定的元素類型返回一個新的切片類型。
func (s *Slice) Elem() Type
Elem返回切片的元素類型。
func (t *Slice) String() string
func (t *Slice) Underlying() Type
StdSizes是創(chuàng)建常用大小的便利類型。它做出以下簡化假設(shè):
- 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實現(xiàn)大小。
type StdSizes struct { WordSize int64 // word size in bytes - must be >= 4 (32bits) MaxAlign int64 // maximum alignment in bytes - must be >= 1}
func (s *StdSizes) Alignof(T Type) int64
func (s *StdSizes) Offsetsof(fields []*Var) []int64
func (s *StdSizes) Sizeof(T Type) int64
一個Struct表示一個結(jié)構(gòu)類型。
type Struct struct { // contains filtered or unexported fields}
func NewStruct(fields []*Var, tags []string) *Struct
NewStruct返回一個帶有給定字段和相應(yīng)字段標簽的新結(jié)構(gòu)。如果索引為i的字段有一個標簽,則tagsi必須是該標簽,但len(標簽)可能只有在索引i最大時才需要。因此,如果沒有字段有標簽,標簽可能為零。
func (s *Struct) Field(i int) *Var
Field返回第i個字段0 <= i <NumFields()。
func (s *Struct) NumFields() int
NumFields返回結(jié)構(gòu)中字段的數(shù)量(包括空白字段和匿名字段)。
func (t *Struct) String() string
func (s *Struct) Tag(i int) string
標記為0 <= i <NumFields()返回第i個字段標記。
func (t *Struct) Underlying() Type
一個Tuple表示一個有序的變量列表; 一個零*元組是一個有效的(空)元組。元組被用作簽名的組成部分并表示多個賦值的類型; 他們不是Go的頭等類型。
type Tuple struct { // contains filtered or unexported fields}
func NewTuple(x ...*Var) *Tuple
NewTuple為給定的變量返回一個新的元組。
func (t *Tuple) At(i int) *Var
At返回元組t的第i個變量。
func (t *Tuple) Len() int
Len返回元組t的數(shù)字變量。
func (t *Tuple) String() string
func (t *Tuple) Underlying() Type
Type代表一種Go。所有類型都實現(xiàn)了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(typ Type) Type
Default返回“無類型”類型的默認“類型”類型; 它返回所有其他類型的傳入類型。untyped nil的默認類型是無類型nil。
TypeAndValue報告相應(yīng)表達式的類型和值(對于常量)。
type TypeAndValue struct { Type Type Value constant.Value // contains filtered or unexported fields}
func Eval(fset *token.FileSet, pkg *Package, pos token.Pos, expr string) (TypeAndValue, error)
Eval返回類型,如果常量,則返回表達式expr的值,在包pkg的位置pos處計算,該值必須是從類型檢查AST檢查AST并提供相對于提供的文件集的完整位置信息。
如果表達式包含函數(shù)文字,則忽略它們的正文(即,未對文體進行類型檢查)。
如果pkg == nil,則使用Universe范圍,并忽略所提供的位置pos。如果pkg!= nil且pos無效,則使用軟件包范圍。否則,pos必須屬于包。
如果pos不在包內(nèi)或者無法評估節(jié)點,則會返回錯誤。
注意:不應(yīng)該使用Eval來代替運行Check來計算類型和值,但除了Check之外。Eval每次都會重新評估它的參數(shù),它也不知道使用表達式的上下文(例如,賦值)。因此,頂層的無類型常量將返回一個無類型的類型,而不是相應(yīng)的特定于上下文的類型。
func (tv TypeAndValue) Addressable() bool
Addressable報告相應(yīng)的表達式是否可尋址(https://golang.org/ref/spec#Address_operators)。
func (tv TypeAndValue) Assignable() bool
Assignable報告相應(yīng)的表達式是否可分配給(提供正確類型的值)。
func (tv TypeAndValue) HasOk() bool
HasOk報告相應(yīng)的表達式是否可用于逗號分配的lhs。
func (tv TypeAndValue) IsBuiltin() bool
IsBuiltin報告相應(yīng)的表達式是否表示一個(可能括號內(nèi)的)內(nèi)置函數(shù)。
func (tv TypeAndValue) IsNil() bool
IsNil報告相應(yīng)的表達式是否表示預(yù)先聲明的值nil。
func (tv TypeAndValue) IsType() bool
IsType報告相應(yīng)的表達式是否指定一個類型。
func (tv TypeAndValue) IsValue() bool
IsValue報告相應(yīng)的表達式是否為值。建筑物不被視為價值。常量值具有非零值。
func (tv TypeAndValue) IsVoid() bool
IsVoid報告相應(yīng)的表達式是否是沒有結(jié)果的函數(shù)調(diào)用。
TypeName表示(named或alias)類型的名稱。
type TypeName struct { // contains filtered or unexported fields}
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
IsAlias報告obj是否是某個類型的別名。
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
Variable表示聲明的變量(包括函數(shù)參數(shù)和結(jié)果以及結(jié)構(gòu)體字段)。
type Var struct { // contains filtered or unexported fields}
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