goverter
goverter copied to clipboard
Convert pointer to not pointer and reverse
Is your feature request related to a problem? Please describe.
Today, goverter can return the following error:
TypeMismatch: Cannot convert *float64 to float64
And this can be similar also for structure.
Describe the solution you'd like
I would believe if the type kind is the same, goverter should try to convert:
- if ptr is nil return default value
- convert pointed value
This is by design. My intention for this is, that when converting from X to Y and back again, then the resulting object should be equal. Example:
// goverter:converter
type Converter interface {
Convert1(source Input) Output
Convert2(source Output) Input
}
type Input struct {
Name *string
}
type Output struct {
Name string
}
func doSomething() {
var c Converter = ConverterImpl{}
inputStart := Input{}
output := c.Convert1(inputStart)
inputEnd := c.Convert2(output)
// inputStart != inputEnd
// because inputEnd.Name would be "" instead of a nil pointer
// if goverter returns "" when converting from *string to string
}
Thus, goverter errs when it cannot convert something without losing information.
To work around this, you can define a custom converter method and setting the default value there:
See https://github.com/jmattheis/goverter/blob/main/example/mismatched/input.go
I understand, however I would note that this only happened when the value is nil, all other value would be valid. I strongly believe to add an option/flag to support this behavior would add a lot of value.
@afarbos This is possible to do in copygen:
- Use customized functions OR
- Use converter functions, etc.
With v0.17.0 goverter can automatically convert *float to float when you enable this feature https://goverter.jmattheis.de/#/conversion/misc?id=use-zero-value-on-pointer-inconsistency