Reputation: 4841
I want to return the name of a struct attribute using the reflect package. So far I have:
type MultiQuestions struct {
QuestionId int64
QuestionType string
QuestionText string
}
func (q *MultiQuestions) StructAttrName() string {
return reflect.ValueOf(q).Elem().Field(0).Name
}
However, this gives me a error reflect.ValueOf(q).Elem().Field(0).Name undefined (type reflect.Value has no field or method Name)
I tried casting to StructField but that didn't work either. How do I get at the name of Struct?
In this case, the names I am interested in are QuestionId, QuestionType and QuestionText.
Upvotes: 6
Views: 8131
Reputation: 1324537
You also can consider to utility functions defined in github.com/fatih/structure
, like the Fields(s interface{}) []string
one, which work on pointers or objects, including struct
fields within the struct
.
package main
import (
"fmt"
"reflect"
"github.com/fatih/structure"
)
type MultiQuestions struct {
QuestionId int64
QuestionType string
QuestionText string
SubMQ SubMultiQuestions
}
type SubMultiQuestions struct{}
func (q *MultiQuestions) StructAttrName() string {
return reflect.Indirect(reflect.ValueOf(q)).Type().Field(0).Name
}
func main() {
fmt.Println((&MultiQuestions{}).StructAttrName())
fmt.Println(Fields(&MultiQuestions{}))
fmt.Println(Fields(MultiQuestions{}))
}
Output:
SubMQ
[QuestionId QuestionType QuestionText SubMQ]
[QuestionId QuestionType QuestionText SubMQ]
See a full example in this play.golang.org
Upvotes: 0
Reputation: 48330
Use the Type:
package main
import (
"fmt"
"reflect"
)
type MultiQuestions struct {
QuestionId int64
QuestionType string
QuestionText string
}
func (q *MultiQuestions) StructAttrName() string {
return reflect.TypeOf(q).Elem().Field(0).Name
}
func main() {
fmt.Println((&MultiQuestions{}).StructAttrName())
}
http://play.golang.org/p/su7VIKXBE2
Upvotes: 0
Reputation: 99234
You need to operate on the Type
not the Value
func (q *MultiQuestions) StructAttrName() string {
return reflect.Indirect(reflect.ValueOf(q)).Type().Field(0).Name
}
Upvotes: 6