Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
aQuaYi opened this issue Jan 18, 2018 · 0 comments
Open

Comments

@aQuaYi
Copy link

aQuaYi commented Jan 18, 2018

$ 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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant