goverter icon indicating copy to clipboard operation
goverter copied to clipboard

Convert pointer to not pointer and reverse

Open afarbos opened this issue 2 years ago • 3 comments

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

afarbos avatar Dec 23 '21 18:12 afarbos

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

jmattheis avatar Dec 23 '21 19:12 jmattheis

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 avatar Dec 23 '21 23:12 afarbos

@afarbos This is possible to do in copygen:

switchupcb avatar Feb 17 '22 03:02 switchupcb

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

jmattheis avatar Mar 10 '23 16:03 jmattheis