当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


GO Scope用法及代码示例

GO语言"go/types"包中"Scope"类型的用法及代码示例。

范围维护一组对象并链接到其包含(父)和包含(子)范围。可以按名称插入和查找对象。 Scope 的零值是 ready-to-use 空范围。

用法:

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

Universe 范围包含所有预先声明的 Go 对象。它是任何嵌套范围链的最外层范围。

var Universe *Scope">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
.  .  .  .  }
.  .  .  }
.  .  }
.  }
}

相关用法


注:本文由纯净天空筛选整理自golang.google.cn大神的英文原创作品 Scope。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。