Home > other >  How can we convert []interface{} to struct?
How can we convert []interface{} to struct?

Time:07-15

func process(team Team) GetData {    
    for _, row := range team.Data {
        data := row.(dbtype.Node).Props
        isData := isData(data, user)
        if isData {
            ...
        } 
    }
}

func isData(data map[string]interface{}) bool {
    ...
    return true
}

type Team struct {
    ...
    Data []interface{} `json:"data"`
}

But I don't want to use row.(dbtype.Node).Props line. How can I add a new struct?

I have tried this. But it not working. It is showing error: cannot range over team.Data (variable of type NewData) error.

How can I add struct instead of []interface{}

type Team struct {
    ...
    Data NewData `json:"data"`
}

type NewData struct {
    ...
}

Thank you.

CodePudding user response:

you can type assert the interface{} to a type.

    myType, ok := row.(yourType)
    if ok {
    // use my type
    }

you can find go tour link here https://go.dev/tour/methods/15

CodePudding user response:

Should it not be:

type Team struct {
    ...
    Data []NewData `json:"data"`
}

?

  • Related