Home  >  Article  >  Backend Development  >  golang map transfer

golang map transfer

王林
王林Original
2023-05-19 12:12:09873browse

Change to struct

As Golang becomes increasingly popular in the open source community, more and more developers choose to use this language as the preferred language for building applications. In Golang, map is a very useful data structure. It can be used in many scenarios, such as associative arrays. During the development process, we sometimes need to convert a map into a struct for more convenient operation and management. In this article, we will introduce how to convert map to struct to make it more maintainable and extensible.

Conversion Principle

In Golang, map is an unordered collection composed of key-value pairs. A struct is a collection of data of the same type or different types. Therefore, in the process of converting map to struct, we need to map the key-value in the map to the fields in the struct, which is a one-to-one correspondence.

Conversion steps

Below we will introduce in detail how to convert map to struct.

Step 1: Define struct

First, we need to define a struct to receive the data in the map. For example, we have defined a Person structure, which contains three fields: Name, Age and Gender, as shown below:

type Person struct {
    Name   string
    Age    int
    Gender string
}

Step 2: Define map

Next, we need to define A map with string keys as names and corresponding values ​​as values. For example, we define the following map:

personData := map[string]interface{}{
    "Name":   "Tom",
    "Age":    25,
    "Gender": "Male",
}

Step 3: Convert map

After we have defined a struct and a map, we can perform data conversion. In Golang, there is a very convenient library reflect, which can help us realize the function of converting map to struct. We can use the reflect.ValueOf() method to get the value of the map, and the reflect.TypeOf() method to get the type of the struct. We can then loop through the map and assign its values ​​to the corresponding fields in the struct.

For example, we can write the following code:

func mapToStruct(m map[string]interface{}, s interface{}) error {
    structValue := reflect.ValueOf(s).Elem()

    for key, val := range m {
        fieldName := strings.Title(key)
        fieldValue := structValue.FieldByName(fieldName)

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

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

        fieldType := fieldValue.Type()
        valType := reflect.TypeOf(val)

        if valType.ConvertibleTo(fieldType) {
            newVal := reflect.ValueOf(val).Convert(fieldType)
            fieldValue.Set(newVal)
        }
    }
    return nil
}

Step 4: Test the conversion

After the conversion is completed, we can write a test function to verify whether the conversion is successful. For example, we can write the function in the following way:

func TestMapToStruct(t *testing.T) {
    var person Person
    err := mapToStruct(personData, &person)
    if err != nil {
        t.Error(err)
    }

    if person.Name != "Tom" {
        t.Errorf("Name should be Tom, but got %s", person.Name)
    }

    if person.Age != 25 {
        t.Errorf("Age should be 25, but got %d", person.Age)
    }

    if person.Gender != "Male" {
        t.Errorf("Gender should be Male, but got %s", person.Gender)
    }
}

Summary

Converting a map to a struct is a very common operation in Golang development. This article mainly introduces how to use reflect Library converts map to struct. In this way, we can manage data more conveniently and operate it more flexibly.

The above is the detailed content of golang map transfer. 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
Previous article:golang json errorNext article:golang json error