6

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.

3 Answers 3

6

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
}

playground

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.