Skip to content

Commit 77b4beb

Browse files
andrestcianlancetaylor
authored andcommitted
reflect: handle types with unexported methods before exported ones
The method Method expects index to be an index of exported fields, but, before this change, the index used by MethodByName could take into account unexported fields if those happened sort before the exported one. Fixes #21177 Change-Id: I90bb64a47b23e2e43fdd2b8a1e0a2c9a8a63ded2 Reviewed-on: https://go-review.googlesource.com/51810 Reviewed-by: Ian Lance Taylor <[email protected]> Run-TryBot: Ian Lance Taylor <[email protected]> TryBot-Result: Gobot Gobot <[email protected]>
1 parent e0ab505 commit 77b4beb

File tree

2 files changed

+25
-2
lines changed

2 files changed

+25
-2
lines changed

src/reflect/all_test.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5521,6 +5521,25 @@ func TestKeepFuncLive(t *testing.T) {
55215521
MakeFunc(typ, f).Call([]Value{ValueOf(10)})
55225522
}
55235523

5524+
type UnExportedFirst int
5525+
5526+
func (i UnExportedFirst) ΦExported() {}
5527+
func (i UnExportedFirst) unexported() {}
5528+
5529+
// Issue 21177
5530+
func TestMethodByNameUnExportedFirst(t *testing.T) {
5531+
defer func() {
5532+
if recover() != nil {
5533+
t.Errorf("should not panic")
5534+
}
5535+
}()
5536+
typ := TypeOf(UnExportedFirst(0))
5537+
m, _ := typ.MethodByName("ΦExported")
5538+
if m.Name != "ΦExported" {
5539+
t.Errorf("got %s, expected ΦExported", m.Name)
5540+
}
5541+
}
5542+
55245543
// Issue 18635 (method version).
55255544
type KeepMethodLive struct{}
55265545

src/reflect/type.go

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -871,11 +871,15 @@ func (t *rtype) MethodByName(name string) (m Method, ok bool) {
871871
return Method{}, false
872872
}
873873
utmethods := ut.methods()
874+
var eidx int
874875
for i := 0; i < int(ut.mcount); i++ {
875876
p := utmethods[i]
876877
pname := t.nameOff(p.name)
877-
if pname.isExported() && pname.name() == name {
878-
return t.Method(i), true
878+
if pname.isExported() {
879+
if pname.name() == name {
880+
return t.Method(eidx), true
881+
}
882+
eidx++
879883
}
880884
}
881885
return Method{}, false

0 commit comments

Comments
 (0)