What is idiomatic way to find if struct field is exported or not?

3,076 views
Skip to first unread message

Tad Vi

unread,
Apr 26, 2016, 3:10:34 PM4/26/16
to golang-nuts
While reviewing number of popular packages online I noticed different approaches to the same problem:
how to find if struct field is exported or not?

Some use PkgPath and check if it is empty:

// skip unexported fields
if len(f.PkgPath) != 0 {
continue
}

Some check if field is settable something like:

// Don't even bother for unexported fields.
if !v.CanSet() {
return nil
}

Stdlib does not seem to have IsExported() so question is: which way is idiomatic?


Tim K

unread,
Apr 26, 2016, 5:55:55 PM4/26/16
to golang-nuts
You could check whether the field name starts with an uppercase, but from the godoc PkgPath already does what you want:

// PkgPath is the package path that qualifies a lower case (unexported)
// field name.  It is empty for upper case (exported) field names.
// See https://golang.org/ref/spec#Uniqueness_of_identifiers

CanSet() covers more cases than unexported fields, I would just use PkgPath instead.

tmaclo...@gmail.com

unread,
Jan 15, 2020, 1:27:42 AM1/15/20
to golang-nuts
if !reflect.ValueOf(strct).Field(i).CanInterface() {
continue
}

在 2016年4月27日星期三 UTC+8上午3:10:34,Tad Vizbaras写道:
Reply all
Reply to author
Forward
0 new messages