jmattheis / goverter

Generate type-safe Go converters by simply defining an interface
https://goverter.jmattheis.de/
MIT License
496 stars 46 forks source link

Convert pointer to not pointer and reverse #11

Closed afarbos closed 1 year ago

afarbos commented 2 years ago

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:

  1. if ptr is nil return default value
  2. convert pointed value
jmattheis commented 2 years ago

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

afarbos commented 2 years ago

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.

switchupcb commented 2 years ago

@afarbos This is possible to do in copygen:

jmattheis commented 1 year ago

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