Skip to content

Metadata doesn't seem to populate when Decoding from a Struct into a map #127

@dakojohn

Description

@dakojohn

Problem:

The metadata struct doesn't seem to populate when Decoding a Struct into a map.

Example:

https://go.dev/play/p/tNdbyQI4GE3

package main

import (
	"fmt"

	"github.com/go-viper/mapstructure/v2"
)

type ExampleStruct struct {
	ID          string `mapstructure:"id"`
	Name        string `mapstructure:"name"`
	Description string `mapstructure:"description"`
	Hidden      string `mapstructure:"-"`
	unexported  string
}

func main() {
	p := &ExampleStruct{
		ID:          "123",
		Name:        "test",
		Description: "desc",
		Hidden:      "hidden",
		unexported:  "unexported value",
	}

	// Use the struct as input to create a map as output
	var resultMap map[string]any
	var metadata mapstructure.Metadata

	// Decode FROM the struct TO a map
	err := mapstructure.DecodeMetadata(p, &resultMap, &metadata)
	if err != nil {
		fmt.Printf("Error decoding: %v\n", err)
		return
	}

	fmt.Printf("Original struct: %+v \n", p)
	fmt.Println("Decode results: ", resultMap)
	fmt.Println("Metadata Keys:  ", metadata.Keys)
	fmt.Println("Metadata Unused:", metadata.Unused)
	fmt.Println("Metadata Unset: ", metadata.Unset)
}

Output:

Original struct: &{ID:123 Name:test Description:desc Hidden:hidden unexported:unexported value} 
Decode results:  map[description:desc id:123 name:test]
Metadata Keys:   []
Metadata Unused: []
Metadata Unset:  []

Program exited.

Expected:

Original struct: &{ID:123 Name:test Description:desc Hidden:hidden unexported:unexported value} 
Decode results:  map[description:desc id:123 name:test]
Metadata Keys:   [id name description]
Metadata Unused: []
Metadata Unset:  [unexported -]

Program exited.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions