Home >Backend Development >Golang >How Can I Directly Convert a Go Map to a Struct Without External Libraries?

How Can I Directly Convert a Go Map to a Struct Without External Libraries?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-27 21:58:13350browse

How Can I Directly Convert a Go Map to a Struct Without External Libraries?

Converting Map to Struct in Go Without Intermediaries

In Go, converting a map to a struct can be achieved in several ways. One approach involves using the mapstructure package, which offers efficient decoding of maps into structs. However, for those seeking a more direct method, here's a custom implementation:

import "reflect"

type MyStruct struct {
    Name string
    Age  int64
}

// SetField sets the value of a struct field by name.
func SetField(obj interface{}, name string, value interface{}) error {
    structValue := reflect.ValueOf(obj).Elem()
    field := structValue.FieldByName(name)

    if !field.IsValid() {
        return fmt.Errorf("No such field: %s in obj", name)
    }

    if !field.CanSet() {
        return fmt.Errorf("Cannot set %s field value", name)
    }

    val := reflect.ValueOf(value)
    if field.Type() != val.Type() {
        return errors.New("Provided value type didn't match obj field type")
    }

    field.Set(val)
    return nil
}

// FillStruct fills the struct fields with values from the map.
func (s *MyStruct) FillStruct(m map[string]interface{}) error {
    for k, v := range m {
        err := SetField(s, k, v)
        if err != nil {
            return err
        }
    }
    return nil
}

func main() {
    data := make(map[string]interface{})
    data["Name"] = "Tony"
    data["Age"] = int64(23)

    result := &MyStruct{}
    err := result.FillStruct(data)
    if err != nil {
        fmt.Println(err)
    }

    fmt.Println(result)
}

In this approach, the SetField function sets the value of a field by its name, ensuring that the field exists, is accessible, and has the correct type. The FillStruct method of the struct then iterates over the map and uses SetField to populate the fields.

The above is the detailed content of How Can I Directly Convert a Go Map to a Struct Without External Libraries?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn