GO語言"go/types"包中"Scope"類型的用法及代碼示例。
範圍維護一組對象並鏈接到其包含(父)和包含(子)範圍。可以按名稱插入和查找對象。 Scope 的零值是 ready-to-use 空範圍。
用法:
type Scope struct {
// contains filtered or unexported fields
}
Universe 範圍包含所有預先聲明的 Go 對象。它是任何嵌套範圍鏈的最外層範圍。
var Universe *Scope
例子:
ExampleScope 打印從一組已解析文件創建的包的範圍樹。
package main
import (
"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.File
for _, 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
func Unused() { {}; {{ var x int; _ = x }} } // make sure empty block scopes get printed
`},
} {
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(), ""))
}
輸出:
package "temperature" scope { . const temperature.Boiling temperature.Celsius . type temperature.Celsius float64 . func temperature.FToC(f float64) temperature.Celsius . func temperature.Unused() . func temperature.main() . main.go scope { . . package fmt . . function scope { . . . var freezing temperature.Celsius . . } . } . celsius.go scope { . . package fmt . . function scope { . . . var c temperature.Celsius . . } . . function scope { . . . var f float64 . . } . . function scope { . . . block scope { . . . } . . . block scope { . . . . block scope { . . . . . var x int . . . . } . . . } . . } . } }
相關用法
- GO Scanner.Scan用法及代碼示例
- GO Scanner用法及代碼示例
- GO Scanner.Bytes用法及代碼示例
- GO StreamWriter用法及代碼示例
- GO Split用法及代碼示例
- GO Server.Shutdown用法及代碼示例
- GO Slice用法及代碼示例
- GO StructTag.Lookup用法及代碼示例
- GO SplitAfter用法及代碼示例
- GO Sum256用法及代碼示例
- GO SectionReader用法及代碼示例
- GO Sin用法及代碼示例
- GO Sprintf用法及代碼示例
- GO Strings用法及代碼示例
- GO SendMail用法及代碼示例
- GO StructTag用法及代碼示例
- GO Stmt用法及代碼示例
- GO Sprint用法及代碼示例
- GO SpecialCase用法及代碼示例
- GO SectionReader.ReadAt用法及代碼示例
注:本文由純淨天空篩選整理自golang.google.cn大神的英文原創作品 Scope。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。