Skip to content

Conversation

tomdevelops
Copy link
Contributor

You can add now converter functions as an option, to convert type A to to type B.

I took some inspiration from PR #90, but implemented it a little bit diffrent. Some of the diffrences are as follows:

  • passed it as an option
  • no instances
  • no exposure of reflect package
  • no external module dependencies

Example

func main() {
	type SrcStruct struct {
		Field1 time.Time
		Field2 *time.Time
	}

	type DestStruct struct {
		Field1 string
		Field2 string
	}

	testTime := time.Date(2021, 3, 5, 1, 30, 0, 123000000, time.UTC)

	src := SrcStruct{
		Field1: testTime,
		Field2: &testTime,
	}

	var dst DestStruct

	err := copier.CopyWithOption(&dst, &src, copier.Option{
		IgnoreEmpty: true,
		DeepCopy:    true,
		Converters: []copier.TypeConverter{
			{
				SrcType: time.Time{},
				DstType: copier.String,
				Fn: func(src interface{}) (interface{}, error) {
					s, ok := src.(time.Time)

					if !ok {
						return nil, errors.New("src type not matching")
					}

					return s.Format(time.RFC3339), nil
				},
			},
		},
	})

	if err != nil {
		log.Fatal(err)
	}
	
	// DestStruct{Field1:"2021-03-05T01:30:00Z", Field2:"2021-03-05T01:30:00Z"}
	fmt.Printf("%#v", dst)
}

Feel free to make suggestions to any part of the PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants