GO語言"go/types"包中"MethodSet"類型的用法及代碼示例。
MethodSet 是一組有序的具體或抽象(接口)方法;一個方法是一個MethodVal選擇,它們按m.Obj().Id()升序排列。 MethodSet 的零值是 ready-to-use 空方法集。
用法:
type MethodSet struct {
// contains filtered or unexported fields
}
例子:
ExampleMethodSet 打印各種類型的方法集。
package main
import (
"fmt"
"go/ast"
"go/importer"
"go/parser"
"go/token"
"go/types"
"log"
)
func main() {
// Parse a single source file.
const input = `
package temperature
import "fmt"
type Celsius float64
func (c Celsius) String() string { return fmt.Sprintf("%g°C", c) }
func (c *Celsius) SetF(f float64) { *c = Celsius(f - 32 / 9 * 5) }
type S struct { I; m int }
type I interface { m() byte }
`
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "celsius.go", input, 0)
if err != nil {
log.Fatal(err)
}
// Type-check a package consisting of this file.
// Type information for the imported packages
// comes from $GOROOT/pkg/$GOOS_$GOOARCH/fmt.a.
conf := types.Config{Importer: importer.Default()}
pkg, err := conf.Check("temperature", fset, []*ast.File{f}, nil)
if err != nil {
log.Fatal(err)
}
// Print the method sets of Celsius and *Celsius.
celsius := pkg.Scope().Lookup("Celsius").Type()
for _, t := range []types.Type{celsius, types.NewPointer(celsius)} {
fmt.Printf("Method set of %s:\n", t)
mset := types.NewMethodSet(t)
for i := 0; i < mset.Len(); i++ {
fmt.Println(mset.At(i))
}
fmt.Println()
}
// Print the method set of S.
styp := pkg.Scope().Lookup("S").Type()
fmt.Printf("Method set of %s:\n", styp)
fmt.Println(types.NewMethodSet(styp))
}
輸出:
Method set of temperature.Celsius: method (temperature.Celsius) String() string Method set of *temperature.Celsius: method (*temperature.Celsius) SetF(f float64) method (*temperature.Celsius) String() string Method set of temperature.S: MethodSet {}
相關用法
- GO MakeFunc用法及代碼示例
- GO Mul32用法及代碼示例
- GO Mkdir用法及代碼示例
- GO Map用法及代碼示例
- GO MkdirTemp用法及代碼示例
- GO MakeTable用法及代碼示例
- GO Modf用法及代碼示例
- GO Mul64用法及代碼示例
- GO Mod用法及代碼示例
- GO MultiReader用法及代碼示例
- GO MultiWriter用法及代碼示例
- GO MarshalIndent用法及代碼示例
- GO Marshal用法及代碼示例
- GO MatchString用法及代碼示例
- GO Month用法及代碼示例
- GO Match用法及代碼示例
- GO MkdirAll用法及代碼示例
- GO PutUvarint用法及代碼示例
- GO Scanner.Scan用法及代碼示例
- GO LeadingZeros32用法及代碼示例
注:本文由純淨天空篩選整理自golang.google.cn大神的英文原創作品 MethodSet。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。