jmattheis / goverter

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

Proposal: generate conversion function by defining a type #34

Closed seeflood closed 1 year ago

seeflood commented 1 year ago

Is your feature request related to a problem? Please describe. Currently we have to define an interface before generating the code:

// goverter:converter
type Converter interface {
  Convert(source []Input) []Output
}

And the usage code looks like:

output := &ConverterImpl{}.Convert(input)

It's cool, but a little bit uncommon, because the &ConverterImpl{} looks redundant.

Describe the solution you'd like We can generate conversion function by defining a type.

For example, we define a type:

// goverter:name Convert
type _ func(source []Input) []Output

This definition gives the tool enough information to generate the code. The generated code looks like:

func Convert(source []Input) []Output{
//.....
}

We can invoke the generated function without the redundant &ConverterImpl{} :

output := Convert(input)
jmattheis commented 1 year ago

You could do something like this, then you don't have to instantiate the impl every time:

var Conv = (*ConverterImpl)(nil)

func DoSomething() {
    output := Conv.Convert(input)
}

I'm not really sure about the type definitions for generating the functions, because this would prevent reusing the conversion methods in custom extend methods like described in https://github.com/jmattheis/goverter#reuse-generated-converter

Also, the interface scopes the methods, so you could define two converter interfaces with different mappings and they won't interfere with each other. If there are only top level functions, this won't be possible.

This sounds like a nice feature, but I don't think it'll be worth the development effort.

jmattheis commented 2 months ago

This feature is now supported in v1.5.0. See Guide: Input/output formats