go 的 reflect 能按代码顺序获取 Method 吗?
如下,我希望能按方法在代码中的位置顺序获取方法,但go的反射似乎都会按照名称排序返回,我的需求有实现的方案吗?
1. 运行环境
go version go 1.16+
2. 问题描述?
代码:
type MyService struct{}
func (s *MyService) F1() {}
func (s *MyService) F3() {}
func (s *MyService) F5() {}
func (s *MyService) F2() {}
func (s *MyService) F4() {}
func (s *MyService) F6() {}
func TestReflect(t *testing.T) {
s := &MyService{}
rt := reflect.TypeOf(s)
for i := 0; i < rt.NumMethod(); i++ {
fmt.Println(rt.Method(i).Name)
}
}
3. 您期望得到的结果?
=== RUN TestReflect
F1
F3
F5
F2
F4
F6
--- PASS: TestReflect (0.00s)
4. 您实际得到的结果?
=== RUN TestReflect
F1
F2
F3
F4
F5
F6
--- PASS: TestReflect (0.00s)
输出: