aboutsummaryrefslogtreecommitdiff
path: root/go
diff options
context:
space:
mode:
authorAlan Donovan <adonovan@google.com>2014-11-17 13:54:36 -0500
committerAlan Donovan <adonovan@google.com>2014-11-17 13:54:36 -0500
commit89c9513804940b8e6054380737c2c345db5b86b2 (patch)
tree18331e4d70b690beabb2594fbc7da71d55df432c /go
parentd75c6bdb8faea29fd211f909798f42fbd2377860 (diff)
downloadtools-89c9513804940b8e6054380737c2c345db5b86b2.tar.gz
go/types/typeutil: add an example of Map usage.
LGTM=gri R=gri CC=golang-codereviews https://golang.org/cl/177740043
Diffstat (limited to 'go')
-rw-r--r--go/types/typeutil/example_test.go66
1 files changed, 66 insertions, 0 deletions
diff --git a/go/types/typeutil/example_test.go b/go/types/typeutil/example_test.go
new file mode 100644
index 0000000..6fe9279
--- /dev/null
+++ b/go/types/typeutil/example_test.go
@@ -0,0 +1,66 @@
+package typeutil_test
+
+import (
+ "fmt"
+ "sort"
+
+ "go/ast"
+ "go/parser"
+ "go/token"
+
+ "golang.org/x/tools/go/types"
+ "golang.org/x/tools/go/types/typeutil"
+
+ _ "golang.org/x/tools/go/gcimporter" // no imports; why is this necessary?
+)
+
+func ExampleMap() {
+ const source = `package P
+
+var X []string
+var Y []string
+
+const p, q = 1.0, 2.0
+
+func f(offset int32) (value byte, ok bool)
+func g(rune) (uint8, bool)
+`
+
+ // Parse and type-check the package.
+ fset := token.NewFileSet()
+ f, err := parser.ParseFile(fset, "P.go", source, 0)
+ if err != nil {
+ panic(err)
+ }
+ pkg, err := new(types.Config).Check("P", fset, []*ast.File{f}, nil)
+ if err != nil {
+ panic(err)
+ }
+
+ scope := pkg.Scope()
+
+ // Group names of package-level objects by their type.
+ var namesByType typeutil.Map // value is []string
+ for _, name := range scope.Names() {
+ T := scope.Lookup(name).Type()
+
+ names, _ := namesByType.At(T).([]string)
+ names = append(names, name)
+ namesByType.Set(T, names)
+ }
+
+ // Format, sort, and print the map entries.
+ var lines []string
+ namesByType.Iterate(func(T types.Type, names interface{}) {
+ lines = append(lines, fmt.Sprintf("%s %s", names, T))
+ })
+ sort.Strings(lines)
+ for _, line := range lines {
+ fmt.Println(line)
+ }
+
+ // Output:
+ // [X Y] []string
+ // [f g] func(offset int32) (value byte, ok bool)
+ // [p q] untyped float
+}