jmattheis / goverter

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

Improve struct code-generation for pointer fields #97

Closed jmattheis closed 2 months ago

jmattheis commented 9 months ago

For this converter interface

// goverter:converter
type Converter interface {
    Convert(*Input) *Output
}

type Input struct {
    Age  int
    Name *string
}
type Output struct {
    Age  int
    Name *string
}

goverter will generate this code

func (c *ConverterImpl) Convert(source *example.Input) *example.Output {
    var pExampleOutput *example.Output
    if source != nil {
        var exampleOutput example.Output
        exampleOutput.Age = (*source).Age
        var pString *string
        if (*source).Name != nil {
            xstring := *(*source).Name
            pString = &xstring
        }
        exampleOutput.Name = pString
        pExampleOutput = &exampleOutput
    }
    return pExampleOutput
}

This could be simplified to:

func (c *ConverterImpl) Convert(source *example.Input) *example.Output {
    var pExampleOutput *example.Output
    if source != nil {
        var exampleOutput example.Output
        exampleOutput.Age = (*source).Age
        if (*source).Name != nil {
            xstring := *(*source).Name
            exampleOutput.Name = &xstring
        }
        pExampleOutput = &exampleOutput
    }
    return pExampleOutput
}

This is useful for the default feature. See https://github.com/jmattheis/goverter/pull/96#discussion_r1381973283 & #93

Please :+1: this issue if you like this functionality. If you have a specific use-case in mind, feel free to comment it.

gtchiflidjanov commented 5 months ago

This could be simplified more:

func (c *ConverterImpl) Convert(source *example.Input) *example.Output {
  var pExampleOutput *example.Output
  if source != nil {
    pExampleOutput = & example.Output{
      Age: source.Age,
      Name: source.Name,
    }
  }
  return pExampleOutput
}