项目作者: jinzhu

项目描述 :
Copier for golang, copy value from struct to struct and more
高级语言: Go
项目地址: git://github.com/jinzhu/copier.git
创建时间: 2013-10-31T05:24:36Z
项目社区:https://github.com/jinzhu/copier

开源协议:MIT License

下载


Copier

I am a copier, I copy everything from one to another

test status

Key Features

  • Field-to-field and method-to-field copying based on matching names
  • Support for copying data:
    • From slice to slice
    • From struct to slice
    • From map to map
  • Field manipulation through tags:
    • Enforce field copying with copier:"must"
    • Override fields even when IgnoreEmpty is set with copier:"override"
    • Exclude fields from being copied with copier:"-"

Getting Started

Installation

To start using Copier, install Go and run go get:

  1. go get -u github.com/jinzhu/copier

Basic

Import Copier into your application to access its copying capabilities

  1. import "github.com/jinzhu/copier"

Basic Copying

  1. type User struct {
  2. Name string
  3. Role string
  4. Age int32
  5. }
  6. func (user *User) DoubleAge() int32 {
  7. return 2 * user.Age
  8. }
  9. type Employee struct {
  10. Name string
  11. Age int32
  12. DoubleAge int32
  13. SuperRole string
  14. }
  15. func (employee *Employee) Role(role string) {
  16. employee.SuperRole = "Super " + role
  17. }
  18. func main() {
  19. user := User{Name: "Jinzhu", Age: 18, Role: "Admin"}
  20. employee := Employee{}
  21. copier.Copy(&employee, &user)
  22. fmt.Printf("%#v\n", employee)
  23. // Output: Employee{Name:"Jinzhu", Age:18, DoubleAge:36, SuperRole:"Super Admin"}
  24. }

Tag Usage Examples

copier:"-" - Ignoring Fields

Fields tagged with copier:"-" are explicitly ignored by Copier during the copying process.

  1. type Source struct {
  2. Name string
  3. Secret string // We do not want this to be copied.
  4. }
  5. type Target struct {
  6. Name string
  7. Secret string `copier:"-"`
  8. }
  9. func main() {
  10. source := Source{Name: "John", Secret: "so_secret"}
  11. target := Target{}
  12. copier.Copy(&target, &source)
  13. fmt.Printf("Name: %s, Secret: '%s'\n", target.Name, target.Secret)
  14. // Output: Name: John, Secret: ''
  15. }

copier:"must" - Enforcing Field Copy

The copier:"must" tag forces a field to be copied, resulting in a panic or an error if the field cannot be copied.

  1. type MandatorySource struct {
  2. Identification int
  3. }
  4. type MandatoryTarget struct {
  5. ID int `copier:"must"` // This field must be copied, or it will panic/error.
  6. }
  7. func main() {
  8. source := MandatorySource{}
  9. target := MandatoryTarget{ID: 10}
  10. // This will result in a panic or an error since ID is a must field but is empty in source.
  11. if err := copier.Copy(&target, &source); err != nil {
  12. log.Fatal(err)
  13. }
  14. }

copier:"must,nopanic" - Enforcing Field Copy Without Panic

Similar to copier:"must", but Copier returns an error instead of panicking if the field is not copied.

  1. type SafeSource struct {
  2. ID string
  3. }
  4. type SafeTarget struct {
  5. Code string `copier:"must,nopanic"` // Enforce copying without panic.
  6. }
  7. func main() {
  8. source := SafeSource{}
  9. target := SafeTarget{Code: "200"}
  10. if err := copier.Copy(&target, &source); err != nil {
  11. log.Fatalln("Error:", err)
  12. }
  13. // This will not panic, but will return an error due to missing mandatory field.
  14. }

copier:"override" - Overriding Fields with IgnoreEmpty

Fields tagged with copier:"override" are copied even if IgnoreEmpty is set to true in Copier options and works for nil values.

  1. type SourceWithNil struct {
  2. Details *string
  3. }
  4. type TargetOverride struct {
  5. Details *string `copier:"override"` // Even if source is nil, copy it.
  6. }
  7. func main() {
  8. details := "Important details"
  9. source := SourceWithNil{Details: nil}
  10. target := TargetOverride{Details: &details}
  11. copier.CopyWithOption(&target, &source, copier.Option{IgnoreEmpty: true})
  12. if target.Details == nil {
  13. fmt.Println("Details field was overridden to nil.")
  14. }
  15. }

Specifying Custom Field Names

Use field tags to specify a custom field name when the source and destination field names do not match.

  1. type SourceEmployee struct {
  2. Identifier int64
  3. }
  4. type TargetWorker struct {
  5. ID int64 `copier:"Identifier"` // Map Identifier from SourceEmployee to ID in TargetWorker
  6. }
  7. func main() {
  8. source := SourceEmployee{Identifier: 1001}
  9. target := TargetWorker{}
  10. copier.Copy(&target, &source)
  11. fmt.Printf("Worker ID: %d\n", target.ID)
  12. // Output: Worker ID: 1001
  13. }

Other examples

Copy from Method to Field with Same Name

Illustrates copying from a method to a field and vice versa.

  1. // Assuming User and Employee structs defined earlier with method and field respectively.
  2. func main() {
  3. user := User{Name: "Jinzhu", Age: 18}
  4. employee := Employee{}
  5. copier.Copy(&employee, &user)
  6. fmt.Printf("DoubleAge: %d\n", employee.DoubleAge)
  7. // Output: DoubleAge: 36, demonstrating method to field copying.
  8. }

Copy Struct to Slice

  1. func main() {
  2. user := User{Name: "Jinzhu", Age: 18, Role: "Admin"}
  3. var employees []Employee
  4. copier.Copy(&employees, &user)
  5. fmt.Printf("%#v\n", employees)
  6. // Output: []Employee{{Name: "Jinzhu", Age: 18, DoubleAge: 36, SuperRole: "Super Admin"}}
  7. }

Copy Slice to Slice

  1. func main() {
  2. users := []User{{Name: "Jinzhu", Age: 18, Role: "Admin"}, {Name: "jinzhu 2", Age: 30, Role: "Dev"}}
  3. var employees []Employee
  4. copier.Copy(&employees, &users)
  5. fmt.Printf("%#v\n", employees)
  6. // Output: []Employee{{Name: "Jinzhu", Age: 18, DoubleAge: 36, SuperRole: "Super Admin"}, {Name: "jinzhu 2", Age: 30, DoubleAge: 60, SuperRole: "Super Dev"}}
  7. }

Copy Map to Map

  1. func main() {
  2. map1 := map[int]int{3: 6, 4: 8}
  3. map2 := map[int32]int8{}
  4. copier.Copy(&map2, map1)
  5. fmt.Printf("%#v\n", map2)
  6. // Output: map[int32]int8{3:6, 4:8}
  7. }

Complex Data Copying: Nested Structures with Slices

This example demonstrates how Copier can be used to copy data involving complex, nested structures, including slices of structs, to showcase its ability to handle intricate data copying scenarios.

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/jinzhu/copier"
  5. )
  6. type Address struct {
  7. City string
  8. Country string
  9. }
  10. type Contact struct {
  11. Email string
  12. Phones []string
  13. }
  14. type Employee struct {
  15. Name string
  16. Age int32
  17. Addresses []Address
  18. Contact *Contact
  19. }
  20. type Manager struct {
  21. Name string `copier:"must"`
  22. Age int32 `copier:"must,nopanic"`
  23. ManagedCities []string
  24. Contact *Contact `copier:"override"`
  25. SecondaryEmails []string
  26. }
  27. func main() {
  28. employee := Employee{
  29. Name: "John Doe",
  30. Age: 30,
  31. Addresses: []Address{
  32. {City: "New York", Country: "USA"},
  33. {City: "San Francisco", Country: "USA"},
  34. },
  35. Contact: nil,
  36. }
  37. manager := Manager{
  38. ManagedCities: []string{"Los Angeles", "Boston"},
  39. Contact: &Contact{
  40. Email: "john.doe@example.com",
  41. Phones: []string{"123-456-7890", "098-765-4321"},
  42. }, // since override is set this should be overridden with nil
  43. SecondaryEmails: []string{"secondary@example.com"},
  44. }
  45. copier.CopyWithOption(&manager, &employee, copier.Option{IgnoreEmpty: true, DeepCopy: true})
  46. fmt.Printf("Manager: %#v\n", manager)
  47. // Output: Manager struct showcasing copied fields from Employee,
  48. // including overridden and deeply copied nested slices.
  49. }

Available tags

Tag Description
copier:"-" Explicitly ignores the field during copying.
copier:"must" Forces the field to be copied; Copier will panic or return an error if the field is not copied.
copier:"nopanic" Copier will return an error instead of panicking.
copier:"override" Forces the field to be copied even if IgnoreEmpty is set. Useful for overriding existing values with empty ones
FieldName Specifies a custom field name for copying when field names do not match between structs.

Contributing

You can help to make the project better, check out http://gorm.io/contribute.html for things you can do.

Author

jinzhu

License

Released under the MIT License.