qyuhen / book

学习笔记

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

《Go 语言学习笔记》6.3 方法集 P134 中一个过时的知识点

aQuaYi opened this issue · comments

$ go version
go version go1.9.2 linux/amd64
$ go doc reflect.Type.NumMethod
// NumMethod returns the number of exported methods in the type's method set.
func NumMethod() int

由于现在 t.NumMethod 只统计公开方法的数量,所以需要把 S 和 T 的方法名称改成大写。

package main

import (
	"reflect"
)

type S struct{}

type T struct {
	S
}

func (S) SVal() {}

func (*S) SPtr() {}

func (T) TVal() {}

func (*T) TPtr() {}

func methodSet(a interface{}) {
	t := reflect.TypeOf(a)
	
	for i, n := 0, t.NumMethod(); i < n; i++ {
		m := t.Method(i)
		println(m.Name, m.Type)
	}
}

func main() {
	var t T
	println("-- T's method set-------")
	methodSet(t)
	println("- *T's method set-------")
	methodSet(&t)
}

输出

-- T's method set-------
SVal (0x506ba0,0xc420058060)
TVal (0x506ba0,0xc420058060)
- *T's method set-------
SPtr (0x506ba0,0xc420058120)
SVal (0x506ba0,0xc420058120)
TPtr (0x506ba0,0xc420058120)
TVal (0x506ba0,0xc420058120)