README

structmap

Go Report Card Codecov Build Status Go docs

A go package for converting structs to maps, and maps to structs.

I mostly wrote this for fun and to learn how to use reflection in Go. I don't recommend using this package, because like it and similar libraries it is a complex solution where a simpler one can be used instead. See the why not section below.

Usage

See the example in Go Doc.

Why not to use this or similar packages

There is a simpler way to solve this problem in many cases:

type S {
  A string
  B int
}

func (s *S) Map() map[string]interface{} {
	return map[string]interface{}{
		"A": s.A,
		"B": s.B,
	}
}

func NewWithMap(m map[string]interface{}) *S {
	return &S{
		A: m["A"].(string),
		B: m["B"].(int),
	}
}

func main() {
  s := S{
    A: "text",
    B: 123,
  }

  m := s.Map()
  // m is map[A:text B:123]

  s2 := NewWithMap(m)
  // s2 is {text 123}
}

Documentation

Overview

    Package structmap converts structs to maps, and maps to structs.

    Index

    Examples

    Constants

    This section is empty.

    Variables

    This section is empty.

    Functions

    func Map

    func Map(s interface{}) map[string]interface{}

      Map converts a struct to a map of field names to values.

      Example
      Output:
      
      text 123
      

      func Struct

      func Struct(m map[string]interface{}, s interface{})

        Struct fills a struct with the values in the map.

        Example
        Output:
        
        {text 123}
        

        Types

        This section is empty.

        Source Files