jmattheis / goverter

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

Convert/copy to existing instance #147

Open jmattheis opened 1 month ago

jmattheis commented 1 month ago

Currently goverter always instantiates the target type itself. Sometimes there is already an instance of the target type and you just want to copy the source fields to the target field. Example:

// goverter:converter
type Converter interface {
    CopyTo(source Input, target *Output)
}

type Input struct {
    Age  int
}

type Output struct {
    Name string
    Age  int
}

func use() {
    c := ConverterImpl{}

    source := Input{Age: 42}
    output := Output{Name: "jmattheis"}

    c.CopyTo(source, &output)

    // output.Name = "jmattheis"
    // output.Age = 42
}

Mapstruct has similar functionality:

@Mapper
public interface CarMapper {
    void updateCarFromDto(CarDto carDto, @MappingTarget Car car);
}

https://mapstruct.org/documentation/1.5/reference/html/#updating-bean-instances

See https://github.com/jmattheis/goverter/issues/146#issuecomment-2161457915 for another use-case.

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

dhirajsb commented 4 weeks ago

Is there also a general use case for supporting factory functions to provide the target instance?

jmattheis commented 4 weeks ago

@dhirajsb Could you create a new ticket with a use case? I don't want to fill this ticket with not closely related requests.