### Install Copier Go Package Source: https://github.com/jinzhu/copier/blob/master/README.md Install the Copier library using go get. Ensure Go is installed. ```bash go get -u github.com/jinzhu/copier ``` -------------------------------- ### Copy Data Between Maps Source: https://context7.com/jinzhu/copier/llms.txt Copier supports copying between maps, handling compatible key and value types and performing automatic type conversions when possible. This example shows copying from an int-keyed map to an int32-keyed map and from a string-keyed map to another string-keyed map. ```go package main import ( "fmt" "github.com/jinzhu/copier" ) func main() { source := map[int]int{1: 10, 2: 20, 3: 30} var dest map[int32]int64 copier.Copy(&dest, source) fmt.Printf("Destination map: %#v\n", dest) // Output: Destination map: map[int32]int64{1:10, 2:20, 3:30} // String maps strSource := map[string]string{"key1": "value1", "key2": "value2"} strDest := map[string]string{} copier.Copy(&strDest, strSource) fmt.Printf("String map: %#v\n", strDest) // Output: String map: map[string]string{"key1":"value1", "key2":"value2"} } ``` -------------------------------- ### Copy Between Slices of Different Struct Types Source: https://context7.com/jinzhu/copier/llms.txt This example demonstrates copying data between slices where the source and destination element types are different structs. Copier transforms each element from the source slice to the destination slice type. Ensure the destination slice is initialized or a pointer to it. ```go package main import ( "fmt" "github.com/jinzhu/copier" ) type User struct { Name string Age int32 Role string } type Employee struct { Name string Age int32 } func main() { users := []User{ {Name: "Alice", Age: 30, Role: "Engineer"}, {Name: "Bob", Age: 25, Role: "Designer"}, {Name: "Charlie", Age: 35, Role: "Manager"}, } var employees []Employee copier.Copy(&employees, &users) for _, emp := range employees { fmt.Printf("Name: %s, Age: %d\n", emp.Name, emp.Age) } // Output: // Name: Alice, Age: 30 // Name: Bob, Age: 25 // Name: Charlie, Age: 35 } ``` -------------------------------- ### Implement Custom Type Conversion with `TypeConverter` Source: https://context7.com/jinzhu/copier/llms.txt Use `copier.Option` with `Converters` to define custom logic for converting between specific source and destination types. This example shows converting a comma-separated string to a slice of strings and a float64 to an int. ```go package main import ( "fmt" "strings" "github.com/jinzhu/copier" ) type Source struct { Name string Tags string // comma-separated Score float64 } type Target struct { Name string Tags []string Score int } func main() { source := Source{Name: "Item", Tags: "go,copier,library", Score: 95.7} target := Target{} copier.CopyWithOption(&target, &source, copier.Option{ Converters: []copier.TypeConverter{ { SrcType: copier.String, DstType: []string{}, // Matches any string slice type Fn: func(src interface{}) (interface{}, error) { s := src.(string) if s == "" { return []string{}, nil } return strings.Split(s, ","), nil }, }, { SrcType: copier.Float64, DstType: copier.Int, Fn: func(src interface{}) (interface{}, error) { return int(src.(float64)), nil }, }, }, }) fmt.Printf("Name: %s\n", target.Name) // Output: Name: Item fmt.Printf("Tags: %v\n", target.Tags) // Output: Tags: [go copier library] fmt.Printf("Score: %d\n", target.Score) // Output: Score: 95 } ``` -------------------------------- ### Complex Nested Data Copying with Options Source: https://github.com/jinzhu/copier/blob/master/README.md Demonstrates copying complex nested structures, including slices and pointers, using `CopyWithOption`. Options like `IgnoreEmpty` and `DeepCopy` can be utilized for fine-grained control. ```go package main import ( "fmt" "github.com/jinzhu/copier" ) type Address struct { City string Country string } type Contact struct { Email string Phones []string } type Employee struct { Name string Age int32 Addresses []Address Contact *Contact } type Manager struct { Name string `copier:"must"` Age int32 `copier:"must,nopanic"` ManagedCities []string Contact *Contact `copier:"override"` SecondaryEmails []string } func main() { employee := Employee{ Name: "John Doe", Age: 30, Addresses: []Address{ {City: "New York", Country: "USA"}, {City: "San Francisco", Country: "USA"}, }, Contact: nil, } manager := Manager{ ManagedCities: []string{"Los Angeles", "Boston"}, Contact: &Contact{ Email: "john.doe@example.com", Phones: []string{"123-456-7890", "098-765-4321"}, }, // since override is set this should be overridden with nil SecondaryEmails: []string{"secondary@example.com"}, } copier.CopyWithOption(&manager, &employee, copier.Option{IgnoreEmpty: true, DeepCopy: true}) fmt.Printf("Manager: %#v\n", manager) // Output: Manager struct showcasing copied fields from Employee, // including overridden and deeply copied nested slices. } ``` -------------------------------- ### Advanced Copying with Copier.CopyWithOption Source: https://context7.com/jinzhu/copier/llms.txt Provides fine-grained control over copying using the Option struct. Options include ignoring empty values, deep copying, case-insensitive matching, custom converters, and field mappings. ```go package main import ( "fmt" "github.com/jinzhu/copier" ) type Source struct { Name string Email string Age int Details *string } type Target struct { Name string Email string Age int Details *string `copier:"override"` } func main() { details := "existing details" source := Source{Name: "John", Email: "", Age: 0, Details: nil} target := Target{Name: "Jane", Email: "jane@example.com", Age: 25, Details: &details} err := copier.CopyWithOption(&target, &source, copier.Option{ IgnoreEmpty: true, // Skip copying zero/empty values DeepCopy: true, // Create deep copies of nested structures }) if err != nil { panic(err) } fmt.Printf("Name: %s\n", target.Name) // Output: Name: John (copied) fmt.Printf("Email: %s\n", target.Email) // Output: Email: jane@example.com (preserved, source was empty) fmt.Printf("Age: %d\n", target.Age) // Output: Age: 25 (preserved, source was 0) fmt.Printf("Details: %v\n", target.Details) // Output: Details: (override tag forces copy) } ``` -------------------------------- ### Basic Field Copying Source: https://github.com/jinzhu/copier/blob/master/README.md Demonstrates basic field-to-field copying between structs. Copier matches fields by name and can also copy from methods to fields. ```go type User struct { Name string Role string Age int32 } func (user *User) DoubleAge() int32 { return 2 * user.Age } type Employee struct { Name string Age int32 DoubleAge int32 SuperRole string } func (employee *Employee) Role(role string) { employee.SuperRole = "Super " + role } func main() { user := User{Name: "Jinzhu", Age: 18, Role: "Admin"} employee := Employee{} copier.Copy(&employee, &user) fmt.Printf("%#v\n", employee) // Output: Employee{Name:"Jinzhu", Age:18, DoubleAge:36, SuperRole:"Super Admin"} } ``` -------------------------------- ### Copy from Method to Field Source: https://github.com/jinzhu/copier/blob/master/README.md Demonstrates copying data from a method (e.g., `DoubleAge` in `User`) to a field with the same name in the target struct (`Employee`). ```go // Assuming User and Employee structs defined earlier with method and field respectively. func main() { user := User{Name: "Jinzhu", Age: 18} employee := Employee{} copier.Copy(&employee, &user) fmt.Printf("DoubleAge: %d\n", employee.DoubleAge) // Output: DoubleAge: 36, demonstrating method to field copying. } ``` -------------------------------- ### Import Copier Package Source: https://github.com/jinzhu/copier/blob/master/README.md Import the Copier package into your Go application to use its functionalities. ```go import "github.com/jinzhu/copier" ``` -------------------------------- ### Basic Struct Copying with Copier.Copy Source: https://context7.com/jinzhu/copier/llms.txt Copies matching fields from a source struct to a destination struct. Supports copying method return values and invoking destination methods with source field values. ```go package main import ( "fmt" "github.com/jinzhu/copier" ) type User struct { Name string Role string Age int32 } func (user *User) DoubleAge() int32 { return 2 * user.Age } type Employee struct { Name string Age int32 DoubleAge int32 SuperRole string } func (employee *Employee) Role(role string) { employee.SuperRole = "Super " + role } func main() { user := User{Name: "Jinzhu", Age: 18, Role: "Admin"} employee := Employee{} err := copier.Copy(&employee, &user) if err != nil { panic(err) } fmt.Printf("%#v\n", employee) // Output: Employee{Name:"Jinzhu", Age:18, DoubleAge:36, SuperRole:"Super Admin"} } ``` -------------------------------- ### Enforce Field Copy Without Panic (copier:"must,nopanic") Source: https://github.com/jinzhu/copier/blob/master/README.md Use `copier:"must,nopanic"` to enforce field copying but return an error instead of panicking if the field is missing or cannot be copied. ```go type SafeSource struct { ID string } type SafeTarget struct { Code string `copier:"must,nopanic"` // Enforce copying without panic. } func main() { source := SafeSource{} target := SafeTarget{Code: "200"} if err := copier.Copy(&target, &source); err != nil { log.Fatalln("Error:", err) } // This will not panic, but will return an error due to missing mandatory field. } ``` -------------------------------- ### Copy Map to Map Source: https://github.com/jinzhu/copier/blob/master/README.md Copies key-value pairs from one map to another. The destination map's key and value types should be compatible with the source map. ```go func main() { map1 := map[int]int{3: 6, 4: 8} map2 := map[int32]int8{} copier.Copy(&map2, map1) fmt.Printf("%#v\n", map2) // Output: map[int32]int8{3:6, 4:8} } ``` -------------------------------- ### Copy Slice to Slice Source: https://github.com/jinzhu/copier/blob/master/README.md Copies elements from a slice of structs to another slice of structs. Each element in the source slice is copied to a corresponding element in the destination slice. ```go func main() { users := []User{{Name: "Jinzhu", Age: 18, Role: "Admin"}, {Name: "jinzhu 2", Age: 30, Role: "Dev"}} var employees []Employee copier.Copy(&employees, &users) fmt.Printf("%#v\n", employees) // Output: []Employee{{Name: "Jinzhu", Age: 18, DoubleAge: 36, SuperRole: "Super Admin"}, {Name: "jinzhu 2", Age: 30, DoubleAge: 60, SuperRole: "Super Dev"}} } ``` -------------------------------- ### Specify Custom Field Names with Tags Source: https://github.com/jinzhu/copier/blob/master/README.md Use field tags like `copier:"SourceFieldName"` to map fields from the source struct to different field names in the target struct. ```go type SourceEmployee struct { Identifier int64 } type TargetWorker struct { ID int64 `copier:"Identifier"` // Map Identifier from SourceEmployee to ID in TargetWorker } func main() { source := SourceEmployee{Identifier: 1001} target := TargetWorker{} copier.Copy(&target, &source) fmt.Printf("Worker ID: %d\n", target.ID) // Output: Worker ID: 1001 } ``` -------------------------------- ### Programmatic Field Mapping with copier.FieldNameMapping Source: https://context7.com/jinzhu/copier/llms.txt Use FieldNameMapping to define custom mappings between source and destination struct fields when struct tags are not feasible. Ensure the types and field names match the intended mapping. ```go package main import ( "fmt" "github.com/jinzhu/copier" ) type LegacyUser struct { UserIdentifier int64 DisplayName string EmailAddress string } type ModernUser struct { ID int64 Name string Email string } func main() { legacy := LegacyUser{UserIdentifier: 42, DisplayName: "John", EmailAddress: "john@example.com"} modern := ModernUser{} copier.CopyWithOption(&modern, &legacy, copier.Option{ FieldNameMapping: []copier.FieldNameMapping{ { SrcType: LegacyUser{}, DstType: ModernUser{}, Mapping: map[string]string{ "UserIdentifier": "ID", "DisplayName": "Name", "EmailAddress": "Email", }, }, }, }) fmt.Printf("ID: %d, Name: %s, Email: %s\n", modern.ID, modern.Name, modern.Email) // Output: ID: 42, Name: John, Email: john@example.com } ``` -------------------------------- ### Deep Copying Complex Nested Structures with copier.Option{DeepCopy: true} Source: https://context7.com/jinzhu/copier/llms.txt Utilize DeepCopy: true within copier.Option to perform a full deep copy of nested structures, including embedded structs, pointers, and slices. This ensures modifications to the original nested data do not affect the copied data. ```go package main import ( "fmt" "github.com/jinzhu/copier" ) type Address struct { City string Country string } type Contact struct { Email string Phones []string } type Employee struct { Name string Age int32 Addresses []Address Contact *Contact } type Manager struct { Name string Age int32 Contact *Contact } func main() { employee := Employee{ Name: "John Doe", Age: 35, Addresses: []Address{ {City: "New York", Country: "USA"}, {City: "London", Country: "UK"}, }, Contact: &Contact{ Email: "john@example.com", Phones: []string{"555-0100", "555-0200"}, }, } manager := Manager{} err := copier.CopyWithOption(&manager, &employee, copier.Option{DeepCopy: true}) if err != nil { panic(err) } // Modify original to prove deep copy employee.Contact.Email = "modified@example.com" employee.Contact.Phones[0] = "000-0000" fmt.Printf("Manager Name: %s\n", manager.Name) fmt.Printf("Manager Contact Email: %s\n", manager.Contact.Email) fmt.Printf("Manager Contact Phones: %v\n", manager.Contact.Phones) // Output: // Manager Name: John Doe // Manager Contact Email: john@example.com (unchanged due to deep copy) // Manager Contact Phones: [555-0100 555-0200] (unchanged due to deep copy) } ``` -------------------------------- ### Copy Struct to Slice Source: https://github.com/jinzhu/copier/blob/master/README.md Copies fields from a single struct to a slice of structs. The output slice will contain one element populated from the source struct. ```go func main() { user := User{Name: "Jinzhu", Age: 18, Role: "Admin"} var employees []Employee copier.Copy(&employees, &user) fmt.Printf("%#v\n", employees) // Output: []Employee{{Name: "Jinzhu", Age: 18, DoubleAge: 36, SuperRole: "Super Admin"}} } ``` -------------------------------- ### Override Fields with copier:"override" Source: https://github.com/jinzhu/copier/blob/master/README.md The `copier:"override"` tag allows fields to be copied even when `IgnoreEmpty` is true in copier options. This is useful for copying nil values. ```go type SourceWithNil struct { Details *string } type TargetOverride struct { Details *string `copier:"override"` // Even if source is nil, copy it. } func main() { details := "Important details" source := SourceWithNil{Details: nil} target := TargetOverride{Details: &details} copier.CopyWithOption(&target, &source, copier.Option{IgnoreEmpty: true}) if target.Details == nil { fmt.Println("Details field was overridden to nil.") } } ``` -------------------------------- ### Map Struct Fields with Different Names using `copier` Tag Source: https://context7.com/jinzhu/copier/llms.txt Use the `copier:"FieldName"` tag on destination struct fields to map them to source struct fields with different names. This is useful when source and destination structures do not have identical field names. ```go package main import ( "fmt" "github.com/jinzhu/copier" ) type DatabaseModel struct { UserID int64 FullName string EmailAddr string } type APIResponse struct { ID int64 `copier:"UserID"` Name string `copier:"FullName"` Email string `copier:"EmailAddr"` } func main() { dbModel := DatabaseModel{UserID: 1001, FullName: "John Doe", EmailAddr: "john@example.com"} apiResp := APIResponse{} copier.Copy(&apiResp, &dbModel) fmt.Printf("ID: %d\n", apiResp.ID) // Output: ID: 1001 fmt.Printf("Name: %s\n", apiResp.Name) // Output: Name: John Doe fmt.Printf("Email: %s\n", apiResp.Email) // Output: Email: john@example.com } ``` -------------------------------- ### Ignore Fields with copier:"-" Source: https://github.com/jinzhu/copier/blob/master/README.md Use the `copier:"-"` tag to explicitly exclude fields from being copied. The 'Secret' field in Target will remain its zero value. ```go type Source struct { Name string Secret string // We do not want this to be copied. } type Target struct { Name string Secret string `copier:"-"` } func main() { source := Source{Name: "John", Secret: "so_secret"} target := Target{} copier.Copy(&target, &source) fmt.Printf("Name: %s, Secret: '%s'\n", target.Name, target.Secret) // Output: Name: John, Secret: '' } ``` -------------------------------- ### Enforce Field Copy with copier:"must" Source: https://github.com/jinzhu/copier/blob/master/README.md The `copier:"must"` tag ensures a field is copied. If the field cannot be copied (e.g., missing in source), it will cause a panic or return an error. ```go type MandatorySource struct { Identification int } type MandatoryTarget struct { ID int `copier:"must"` // This field must be copied, or it will panic/error. } func main() { source := MandatorySource{} target := MandatoryTarget{ID: 10} // This will result in a panic or an error since ID is a must field but is empty in source. if err := copier.Copy(&target, &source); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Enforcing Required Fields with copier:"must" Source: https://context7.com/jinzhu/copier/llms.txt Marks a field as mandatory using the `copier:"must"` tag. If the field cannot be copied, Copier will panic or return an error if `nopanic` is also specified. ```go package main import ( "fmt" "github.com/jinzhu/copier" ) type Source struct { ID int Name string } type Target struct { ID int `copier:"must,nopanic"` Name string `copier:"must,nopanic"` } func main() { source := Source{ID: 100, Name: "Product A"} target := Target{} err := copier.Copy(&target, &source) if err != nil { fmt.Printf("Error: %v\n", err) return } fmt.Printf("ID: %d, Name: %s\n", target.ID, target.Name) // Output: ID: 100, Name: Product A // Example with missing required field emptySource := Source{} target2 := Target{} err = copier.Copy(&target2, &emptySource) if err != nil { fmt.Printf("Error: %v\n", err) // Output: Error: field ID has must tag but was not copied } } ``` -------------------------------- ### Copy Single Struct to a Slice Source: https://context7.com/jinzhu/copier/llms.txt The copier library can copy a single struct into a slice. It automatically creates a slice containing the single copied struct as its element. Ensure the destination is a pointer to a slice. ```go package main import ( "fmt" "github.com/jinzhu/copier" ) type User struct { Name string Age int32 Role string } type Employee struct { Name string Age int32 } func main() { user := User{Name: "Alice", Age: 30, Role: "Engineer"} var employees []Employee copier.Copy(&employees, &user) fmt.Printf("Employees: %#v\n", employees) // Output: Employees: []main.Employee{{Name:"Alice", Age:30}} } ``` -------------------------------- ### Ignoring Fields with copier:"-" Tag Source: https://context7.com/jinzhu/copier/llms.txt Explicitly excludes a field from copying using the `copier:"-"` struct tag. Useful for fields that should never be overwritten. ```go package main import ( "fmt" "github.com/jinzhu/copier" ) type Source struct { Name string Secret string Token string } type Target struct { Name string Secret string `copier:"-"` Token string `copier:"-"` } func main() { source := Source{Name: "John", Secret: "password123", Token: "abc-xyz"} target := Target{Secret: "keep-this", Token: "keep-this-too"} copier.Copy(&target, &source) fmt.Printf("Name: %s\n", target.Name) // Output: Name: John fmt.Printf("Secret: %s\n", target.Secret) // Output: Secret: keep-this fmt.Printf("Token: %s\n", target.Token) // Output: Token: keep-this-too } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.