github.com/cockroachdb/tools@v0.0.0-20230222021103-a6d27438930d/go/types/typeutil/example_test.go (about)

     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  
     5  package typeutil_test
     6  
     7  import (
     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  
    18  func ExampleMap() {
    19  	const source = `package P
    20  
    21  var X []string
    22  var Y []string
    23  
    24  const p, q = 1.0, 2.0
    25  
    26  func f(offset int32) (value byte, ok bool)
    27  func g(rune) (uint8, bool)
    28  `
    29  
    30  	// Parse and type-check the package.
    31  	fset := token.NewFileSet()
    32  	f, err := parser.ParseFile(fset, "P.go", source, 0)
    33  	if err != nil {
    34  		panic(err)
    35  	}
    36  	pkg, err := 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(names, name)
    50  		namesByType.Set(T, names)
    51  	}
    52  
    53  	// Format, sort, and print the map entries.
    54  	var lines []string
    55  	namesByType.Iterate(func(T types.Type, names interface{}) {
    56  		lines = append(lines, fmt.Sprintf("%s   %s", names, T))
    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  }