Skip to content

reflect: add StructField.IsExported and Method.IsExported #41563

@dsnet

Description

@dsnet

The StructField.PkgPath field is populated if and only if the field is unexported. However, there is a hit to readability:

for i := 0; i < t.NumField(); i++ {
    f := t.Field(i)
    if f.PkgPath != "" {
        continue
    }
    ...
}

It's not obvious to most readers why the f.PkgPath != "" check exist. For this reason, a vast majority of cases have a comment that says:

    // Skip unexported fields.
    if f.PkgPath != "" {
        continue
    }

This documentation seems unnecessary if we had just added a helper method on StructField like:

// IsExported reports whether the struct field is exported.
func (f StructField) IsExported() bool {
    return f.PkgPath == ""
}

Thus, use of it becomes obvious from a readability perspective:

for i := 0; i < t.NumField(); i++ {
    f := t.Field(i)
    if !f.IsExported() {
        continue
    }
    ...
}

Bikeshedding: I don't have a preference whether this should be called IsExported or simply Exported. The former matches IsValid, IsNil, or IsZero, while the latter matches StructField.Anonymous. It seems that the reflect package is already internally inconsistent about naming of predicate functionality.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions