structmap

package module
v0.0.0-...-765a31a Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 25, 2017 License: MIT Imports: 3 Imported by: 0

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
s := struct {
	A string
	B int
}{
	A: "text",
	B: 123,
}

m := Map(s)

fmt.Println(m["A"], m["B"])
Output:

text 123

func Struct

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

Struct fills a struct with the values in the map.

Example
s := struct {
	A string
	B int
}{}
m := map[string]interface{}{
	"A": "text",
	"B": 123,
}

Struct(m, &s)

fmt.Println(s)
Output:

{text 123}

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL