defaults icon indicating copy to clipboard operation
defaults copied to clipboard

Empty default string does not work with string pointer type.

Open fuhrmannb opened this issue 1 year ago • 1 comments

In this kind of structure:

type A struct {
	StrPtr *string `default:""`
}

A.StrPtr is not set to a pointer of String("") but is still nil.

Example of program highlighting this bug
package main

import (
	"fmt"

	"github.com/creasty/defaults"
)

type A struct {
	StrPtr *string `default:""`
}

func main() {
	var data A
	err := defaults.Set(&data)
	if err != nil {
		panic(err)
	}

	fmt.Println(data.StrPtr)
}

My guess is it's related to https://github.com/creasty/defaults/blob/master/defaults.go#L238 that does not change the field if the tag is empty, or an empty tag could be an empty string here.

I'm wondering if just returning true at the end of the shouldInitializeField method can work or it may break other cases?

fuhrmannb avatar Sep 19 '24 15:09 fuhrmannb

We'd like to utilize Lookup() here to exclude fields without a tag, and then change shouldInitializeField to return true at the end.

https://github.com/creasty/defaults/blob/abebf4bedce8cd6aa1b52cda5a9bc870aa15084d/defaults.go#L36

creasty avatar Sep 24 '24 04:09 creasty