Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added converter option for type conversions #115

Merged
merged 2 commits into from
Jan 19, 2022

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.

None yet

2 participants