How to convert map slice to structure slice with different properties

WBOY
Release: 2024-02-08 22:27:29
forward
758 people have browsed it

How to convert map slice to structure slice with different properties

php editor Xigua introduces you how to convert mapping slices into structural slices with different attributes. In programming, we often encounter situations where we need to convert a map slice into a structure slice with different properties. This transformation helps us better organize and manage data. In this article, we'll introduce a simple yet effective way to implement this transformation, making your code more efficient and flexible. Let’s take a look!

Question content

I am using an api and I need to pass it a struct fragment. I have a map, so I need to convert it to a structure.

package main

import "fmt"

func main() {
    a := []map[string]interface{}{}
    b := make(map[string]interface{})
    c := make(map[string]interface{})
    
    b["prop1"] = "foo"
    b["prop2"] = "bar"
    a = append(a, b)

    c["prop3"] = "baz"
    c["prop4"] = "foobar"
    a = append(a, c)

    fmt.println(a)
}
Copy after login
[map[prop1:foo prop2:bar] map[prop3:baz prop4:foobar]]
Copy after login

So in this example I have a slice of map a which contains b and c which are maps of strings with different keys.

I wish to convert a into a struct slice, where the first element is a struct with prop1 and prop2 as properties, and the second Each element is a structure with prop3 and prop4 as attributes.

is it possible?

I looked at https://github.com/mitchellh/mapstruct but I can't get it to work for my use case. I've seen this answer: https://stackoverflow.com/a/26746461/3390419

Explains how to use the library:

mapstructure.Decode(myData, &result)
Copy after login

However, this seems to assume that the structure where result is an instance is predefined, whereas in my case the structure is dynamic.

Workaround

What you can do is first loop through each map individually, using each map's key-value pairs to build the corresponding reflect.structfield value slice. Once you have such a slice ready, you can pass it to reflect.structof which will return a reflect.type value representing the dynamic struct type, and then You can pass this to reflect.new to create a reflect.value which will represent an instance of the dynamic structure (actually a pointer to the structure).

For example

var result []any
for _, m := range a {
    fields := make([]reflect.StructField, 0, len(m))

    for k, v := range m {
        f := reflect.StructField{
            Name: k,
            Type: reflect.TypeOf(v), // allow for other types, not just strings
        }
        fields = append(fields, f)
    }

    st := reflect.StructOf(fields) // new struct type
    sv := reflect.New(st)          // new struct value

    for k, v := range m {
        sv.Elem(). // dereference struct pointer
                FieldByName(k).         // get the relevant field
                Set(reflect.ValueOf(v)) // set the value of the field
    }

    result = append(result, sv.Interface())
}
Copy after login

https://www.php.cn/link/3722e31eaa9efae6938cc5c435365dfd

The above is the detailed content of How to convert map slice to structure slice with different properties. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:stackoverflow.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!