]> Cypherpunks repositories - gostls13.git/commitdiff
add FieldByName to the interface of reflect.StructType
authorRob Pike <r@golang.org>
Fri, 17 Jul 2009 01:21:14 +0000 (18:21 -0700)
committerRob Pike <r@golang.org>
Fri, 17 Jul 2009 01:21:14 +0000 (18:21 -0700)
R=rsc
DELTA=34  (33 added, 0 deleted, 1 changed)
OCL=31752
CL=31754

src/pkg/reflect/all_test.go
src/pkg/reflect/type.go

index 52e85f411f570b654a4d0e336a1d17c76f97d8da..5a639fb754bcd7e80fbd17dc57e4c05fd697b526 100644 (file)
@@ -214,9 +214,18 @@ func TestAll(t *testing.T) {       // TODO(r): wrap up better
        styp := etyp.(*StructType);
        f := styp.Field(0);
        testType(t, 5, f.Type, "chan *int32");
-       f = styp.Field(1);
+
+       f, present := styp.FieldByName("d");
+       if !present {
+               t.Errorf("FieldByName says present field is absent");
+       }
        testType(t, 6, f.Type, "float32");
 
+       f, present = styp.FieldByName("absent");
+       if present {
+               t.Errorf("FieldByName says absent field is present");
+       }
+
        typ = Typeof(([32]int32)(nil));
        testType(t, 7, typ, "[32]int32");
        testType(t, 8, typ.(*ArrayType).Elem(), "int32");
index fe7619f85d68af12a1b1d9c8c0611657b3d2decb..6a0b70a7a7b5e8e12d47b719cefc9988fa95aed3 100644 (file)
@@ -455,6 +455,7 @@ type StructField struct {
        Type Type;
        Tag string;
        Offset uintptr;
+       Index int;
        Anonymous bool;
 }
 
@@ -482,6 +483,29 @@ func (t *StructType) Field(i int) (f StructField) {
        return;
 }
 
+// FieldByName returns the field with the provided name and a boolean to indicate
+// that the field was found..
+func (t *StructType) FieldByName(name string) (f StructField, present bool) {
+       for i, p := range t.fields {
+               if p.name == nil || *p.name != name {
+                       continue;
+               }
+               f.Name = *p.name;
+               f.Type = toType(*p.typ);
+               if p.pkgPath != nil {
+                       f.PkgPath = *p.pkgPath;
+               }
+               if p.tag != nil {
+                       f.Tag = *p.tag;
+               }
+               f.Offset = p.offset;
+               f.Index = i;
+               present = true;
+               break;
+       }
+       return;
+}
+
 // NumField returns the number of struct fields.
 func (t *StructType) NumField() int {
        return len(t.fields);