structcopygen

package module
v0.0.9 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 11, 2025 License: MIT Imports: 14 Imported by: 0

README

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

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Run

func Run() error

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL