a "type-safe Go converter" generator
goverter is a tool for creating type-safe converters. All you have to do is create an interface and execute goverter. The project is meant as alternative to jinzhu/copier that doesn't use reflection.
Installation แซ Conversion Docs
- Fast execution: No reflection is used at runtime
- Automatically deep copies builtin types: slices, maps, named types, primitive types, pointers, structs with same fields
- Customizable: You can implement custom converter methods
- Clear errors when generating the conversion methods if
- the target struct has unmapped fields
- types cannot be converted without losing information
-
Ensure your
go version
is 1.16 or above -
Create a go modules project if you haven't done so already
$ go mod init module-name
-
Create your converter interface and mark it with a comment containing
goverter:converter
input.go
package example // goverter:converter type Converter interface { ConvertItems(source []Input) []Output // goverter:ignore Irrelevant // goverter:map Nested.AgeInYears Age Convert(source Input) Output } type Input struct { Name string Nested InputNested } type InputNested struct { AgeInYears int } type Output struct { Name string Age int Irrelevant bool }
See Conversion for more information.
-
Run
goverter
:$ go run github.com/jmattheis/goverter/cmd/[email protected] ./
See Installation for more information.
-
goverter created a file at
./generated/generated.go
, it may look like this:package generated import example "goverter/example" type ConverterImpl struct{} func (c *ConverterImpl) Convert(source example.Input) example.Output { var exampleOutput example.Output exampleOutput.Name = source.Name exampleOutput.Age = source.Nested.AgeInYears return exampleOutput } func (c *ConverterImpl) ConvertItems(source []example.Input) []example.Output { var exampleOutputList []example.Output if source != nil { exampleOutputList = make([]example.Output, len(source)) for i := 0; i < len(source); i++ { exampleOutputList[i] = c.Convert(source[i]) } } return exampleOutputList }
goverter uses SemVer for versioning the cli.
This project is licensed under the MIT License - see the LICENSE file for details
Logo by MariaLetta