structcopy-gen
=========
StructCopyGen is a code generator that creates functions to copy struct-to-struct, slice-of-struct-to-slice-of-struct.
Install
go install github.com/structcopy/structcopy-gen/cmd/structcopy-gen@latest
Usage
Use as a Go generator
//go:generate structcopy-gen
type StructCopyGen interface {
…
}
Notation Table
In defaults, all struct's fields are mapping by their name. In case you need to customize the src, you can use below annotations
| notation |
location |
summary |
:skip_field <dst_field> |
method |
Specify dst_field to skip. |
:match_field <dst_field> <src_field> |
method |
Specify src_field if it's not same as dst_field. |
:match_method <dst_field> <method> |
method |
Specify method to copy. |
:conv <dst_field> <func> |
method |
Specify converter func to use |
:struct_conv <func> |
method |
Specify struct convert func to use. It's required when copy slice of struct |
Sample
To use structcopy-gen, write a generator code in the following convention:
package sample
import (
"time"
"github.com/sample/myapp/entity"
"github.com/sample/myapp/dto"
)
//go:generate structcopy-gen
type StructCopyGen interface {
// :match_method Status String()
CopyUserToUserDTO(src *entity.User) (dst *dto.UserDTO)
// :struct_conv CopyUserToUserDTO
CopyUserListToUserDTOList(src []*entity.User) (dst []*dto.UserDTO)
}
package entity
import (
"time"
)
type User struct {
ID int64
Name string
Status Status
Created time.Time
}
type Status string
func (s Status) String() string {
return string(s)
}
outputs:
package dto
type UserDTO struct {
ID int64
Name string
Status string
Created time.Time
}
StructCopyGen generates code similar to the following:
// Code generated by github.com/structcopy/structcopy-gen. DO NOT EDIT.
package sample
import (
"time"
"github.com/sample/myapp/entity"
"github.com/sample/myapp/dto"
)
func CopyUserToUserDTO(src *entity.User) (dst *dto.UserDTO) {
dst = &dto.UserDTO{}
dst.ID = src.ID
dst.Name = src.Name
dst.Status = src.Status.String()
dst.Created = src.Created
return
}
func CopyUserListToUserDTOList(src []*entity.User) (dst []*dto.UserDTO) {
if len(src) > 0 {
dst = make([]*UserDTO, len(src))
for i, e := range src {
dst[i] = CopyUserToUserDTO(e)
}
}
return
}
Credits
License