GoPLS Viewer

Home|gopls/go/types/typeutil/example_test.go
1// Copyright 2014 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5package typeutil_test
6
7import (
8    "fmt"
9    "go/ast"
10    "go/parser"
11    "go/token"
12    "go/types"
13    "sort"
14
15    "golang.org/x/tools/go/types/typeutil"
16)
17
18func ExampleMap() {
19    const source = `package P
20
21var X []string
22var Y []string
23
24const p, q = 1.0, 2.0
25
26func f(offset int32) (value byte, ok bool)
27func g(rune) (uint8, bool)
28`
29
30    // Parse and type-check the package.
31    fset := token.NewFileSet()
32    ferr := parser.ParseFile(fset"P.go"source0)
33    if err != nil {
34        panic(err)
35    }
36    pkgerr := new(types.Config).Check("P"fset, []*ast.File{f}, nil)
37    if err != nil {
38        panic(err)
39    }
40
41    scope := pkg.Scope()
42
43    // Group names of package-level objects by their type.
44    var namesByType typeutil.Map // value is []string
45    for _name := range scope.Names() {
46        T := scope.Lookup(name).Type()
47
48        names_ := namesByType.At(T).([]string)
49        names = append(namesname)
50        namesByType.Set(Tnames)
51    }
52
53    // Format, sort, and print the map entries.
54    var lines []string
55    namesByType.Iterate(func(T types.Typenames interface{}) {
56        lines = append(linesfmt.Sprintf("%s   %s"namesT))
57    })
58    sort.Strings(lines)
59    for _line := range lines {
60        fmt.Println(line)
61    }
62
63    // Output:
64    // [X Y]   []string
65    // [f g]   func(offset int32) (value byte, ok bool)
66    // [p q]   untyped float
67}
68
MembersX
ExampleMap.f
ExampleMap.pkg
ExampleMap.namesByType
ExampleMap.RangeStmt_860.name
ExampleMap.RangeStmt_1246.line
ExampleMap
ExampleMap.source
ExampleMap.err
ExampleMap.scope
ExampleMap.RangeStmt_860.BlockStmt.T
ExampleMap.lines
sort
ExampleMap.fset
Members
X