Skip to content

Default value to the entry that key already exists in a map #28

@nakabonne

Description

@nakabonne

Hi, thank you for making and maintaining such an amazing package. It helps me a lot!

I'm facing an issue that is not able to set default values within a map[string]struct{}. I'd like to set the default value to the entry that key already exists in a map. But it doesn't work well:

package main

import (
	"fmt"

	"github.com/creasty/defaults"
)

type T struct {
	Field string `default:"value-1"`
}

type Foo struct {
	Map map[string]T
	T   T
}

func main() {
	f := &Foo{
		Map: map[string]T{
			// I want to set the default value here.
			"key-1": T{},
		},
	}
	if err := defaults.Set(f); err != nil {
		panic(err)
	}
	fmt.Printf("field in map: %q\n", f.Map["key-1"].Field)
	fmt.Printf("field in struct: %q\n", f.T.Field)

	// Output:
	//
	// field in map: ""
	// field in struct: "value-1"
}

Currently, I workaround like:

	for k, v := range f.Map {
		_ = defaults.Set(&v)
		f.Map[k] = v
	}

Is there another way to set a default value for a value that already has a key in the map?

Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions