Standard library / go/types
go/types.MethodSet.Lookup()
Looks up a method by package and name; returns nil when absent. Expected stdout: 'Read true\n'.
Formal Syntax & Structure
go syntaxgo
func (s *MethodSet) Lookup(pkg *Package, name string) *SelectionParameters & Attributes
| Name | Type | Description |
|---|---|---|
| pkg | *Package | Package containing the symbol; nil for package-independent objects. |
| name | string | Name of the symbol or package. |
Return Value
*Selection
Looks up a method by package and name; returns nil when absent.
Working Example
Example Snippetgo
package main
import ( "fmt" "go/ast" "go/parser" "go/token" "go/types")
func check(e error) { if e != nil { panic(e) }}func methodset() *types.MethodSet { return types.NewMethodSet(object("Item").Type()) }
func object(name string) types.Object { p, _, _ := model(); return p.Scope().Lookup(name) }
func model() (*types.Package, *types.Info, *ast.File) { f := token.NewFileSet() file, err := parser.ParseFile(f, "demo.go", `package demo type Box[T any] struct{ Value T } func (b Box[T]) Get() T { return b.Value } type IntBox = Box[int] type NumberBox[T ~int] struct{ Value T } type Reader interface { Read() int } type NamedReader interface { Reader; Close() } type Item struct { X int } func (i Item) Read() int { return i.X } func Use(i Item) int { _ = Item.Read; return i.X+i.Read() } func Identity[T any](x T) T { return x } func Variadic(x ...int) {} `, 0) check(err) info := &types.Info{Selections: map[*ast.SelectorExpr]*types.Selection{}} p, err := (&types.Config{}).Check("demo", f, []*ast.File{file}, info) check(err) return p, info, file}
func main() { v := methodset() fmt.Println(v.Lookup(nil, "Read").Obj().Name(), v.Lookup(nil, "Missing") == nil)}