>백엔드 개발 >Golang >JSON을 사용하지 않고 Go 맵을 구조체로 효율적으로 변환하려면 어떻게 해야 합니까?

JSON을 사용하지 않고 Go 맵을 구조체로 효율적으로 변환하려면 어떻게 해야 합니까?

Patricia Arquette
Patricia Arquette원래의
2024-12-20 22:26:14858검색

How Can I Efficiently Convert a Go Map to a Struct Without Using JSON?

JSON 없이 지도를 구조체로 변환

Go에서는 지도를 구조체로 변환해야 하는 시나리오를 접할 수 있습니다. JSON은 중개 방법 역할을 할 수 있지만 가장 효율적인 접근 방식은 아닐 수 있습니다. 이 변환을 수행하는 방법은 다음과 같습니다.

한 가지 간단한 대안은 GitHub의 강력한 맵 구조 라이브러리를 사용하는 것입니다. 가져오면 다음과 같이 Decode() 기능을 활용할 수 있습니다.

import "github.com/mitchellh/mapstructure"

mapstructure.Decode(myData, &result)

실습 구현의 경우 다음 접근 방식을 고려하세요.

package main

import (
    "fmt"
    "reflect"
)

type MyStruct struct {
    Name string
    Age  int64
}

func SetField(obj interface{}, name string, value interface{}) error {
    structValue := reflect.ValueOf(obj).Elem()
    structFieldValue := structValue.FieldByName(name)

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

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

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

    structFieldValue.Set(val)
    return nil
}

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() {
    myData := make(map[string]interface{})
    myData["Name"] = "Tony"
    myData["Age"] = int64(23)

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

리플렉션과 사용자 정의 SetField() 함수를 사용하는 이 코드는 맵의 항목을 반복하고 해당 구조체 필드를 설정하여 맵을 구조체로 변환하기 위한 다양한 솔루션을 제공합니다. 가세요.

위 내용은 JSON을 사용하지 않고 Go 맵을 구조체로 효율적으로 변환하려면 어떻게 해야 합니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.