Skip to content
This repository has been archived by the owner on May 2, 2018. It is now read-only.

Commit

Permalink
reflect: make Field panic when out of bounds, as documented
Browse files Browse the repository at this point in the history
Fixes #15046.

Change-Id: Iba7216297735be8e1ec550ce5336d17dcd3fd6b7
Reviewed-on: https://go-review.googlesource.com/22992
Reviewed-by: Brad Fitzpatrick <[email protected]>
Run-TryBot: Brad Fitzpatrick <[email protected]>
Reviewed-by: Ian Lance Taylor <[email protected]>
TryBot-Result: Gobot Gobot <[email protected]>
  • Loading branch information
odeke-em authored and bradfitz committed May 10, 2016
1 parent 42b647b commit 9edb27e
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
35 changes: 35 additions & 0 deletions src/reflect/all_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5221,6 +5221,41 @@ func TestLargeGCProg(t *testing.T) {
fv.Call([]Value{ValueOf([256]*byte{})})
}

func fieldIndexRecover(t Type, i int) (recovered interface{}) {
defer func() {
recovered = recover()
}()

t.Field(i)
return
}

// Issue 15046.
func TestTypeFieldOutOfRangePanic(t *testing.T) {
typ := TypeOf(struct{ X int }{10})
testIndices := [...]struct {
i int
mustPanic bool
}{
0: {-2, true},
1: {0, false},
2: {1, true},
3: {1 << 10, true},
}
for i, tt := range testIndices {
recoveredErr := fieldIndexRecover(typ, tt.i)
if tt.mustPanic {
if recoveredErr == nil {
t.Errorf("#%d: fieldIndex %d expected to panic", i, tt.i)
}
} else {
if recoveredErr != nil {
t.Errorf("#%d: got err=%v, expected no panic", i, recoveredErr)
}
}
}
}

// Issue 9179.
func TestCallGC(t *testing.T) {
f := func(a, b, c, d, e string) {
Expand Down
2 changes: 1 addition & 1 deletion src/reflect/type.go
Original file line number Diff line number Diff line change
Expand Up @@ -1178,7 +1178,7 @@ func (tag StructTag) Lookup(key string) (value string, ok bool) {
// Field returns the i'th struct field.
func (t *structType) Field(i int) (f StructField) {
if i < 0 || i >= len(t.fields) {
return
panic("reflect: Field index out of bounds")
}
p := &t.fields[i]
f.Type = toType(p.typ)
Expand Down

0 comments on commit 9edb27e

Please sign in to comment.