Skip to content

Instantly share code, notes, and snippets.

@uni-3
Created July 24, 2022 13:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uni-3/f91809e69167a124f221dc652e615fa5 to your computer and use it in GitHub Desktop.
Save uni-3/f91809e69167a124f221dc652e615fa5 to your computer and use it in GitHub Desktop.
io.Writer.Writeに定義されている関数の方と名前を参照するスクリプト
package main
import (
"fmt"
"go/types"
"log"
"golang.org/x/tools/go/loader"
)
func main() {
c := loader.Config{}
c.Import("io")
prog, err := c.Load()
if err != nil {
log.Fatal(err)
}
info := prog.Package("io")
ob := info.Pkg.Scope().Lookup("Writer")
fmt.Println("io pkg is loaded and look up Writer interface")
if typ, _ := ob.Type().Underlying().(*types.Interface); typ != nil {
errTyp := types.Universe.Lookup("error").Type().Underlying().(*types.Interface)
byteType := types.Typ[types.Byte]
intType := types.Typ[types.Int]
sig := typ.Method(0).Type().(*types.Signature)
pElem := sig.Params().At(0).Type().(*types.Slice).Elem()
fmt.Printf("method name %#v\n", typ.Method(0).Name())
fmt.Printf("param 0 name %#v\n", sig.Params().At(0).Name())
if types.Identical(pElem, byteType) {
fmt.Println("is type of byte")
}
fmt.Printf("res0 name %#v\n", sig.Results().At(0).Name())
r0Type := sig.Results().At(0).Type()
if types.Identical(r0Type, intType) {
fmt.Println("is type of int")
}
fmt.Printf("res1 name %#v\n", sig.Results().At(1).Name())
r1Type := sig.Results().At(1).Type()
if types.Implements(r1Type, errTyp) {
fmt.Println("implementes error type")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment