diff --git a/docs/convertor.md b/docs/convertor.md index 0d5ff36..7084360 100644 --- a/docs/convertor.md +++ b/docs/convertor.md @@ -39,6 +39,7 @@ import ( - [EncodeByte](#EncodeByte) - [DecodeByte](#DecodeByte) - [DeepClone](#DeepClone) +- [CopyProperties](#CopyProperties)
@@ -691,4 +692,68 @@ func main() { // map[a:1 b:2] false // &{test 1 0.1 trueCopies each field from the source struct into the destination struct.
+ +Signature: + +```go +func CopyProperties[T, U any](dst T, src U) (err error) +``` + +Example: + +```go +package main + +import ( + "fmt" + "github.com/duke-git/lancet/v2/convertor" +) + +func main() { + type Address struct { + Country string + ZipCode string + } + + type User struct { + Name string + Age int + Role string + Addr Address + Hobbys []string + salary int + } + + type Employee struct { + Name string + Age int + Role string + Addr Address + Hobbys []string + salary int + } + + user := User{Name: "user001", Age: 10, Role: "Admin", Addr: Address{Country: "CN", ZipCode: "001"}, Hobbys: []string{"a", "b"}, salary: 1000} + + employee1 := Employee{} + CopyProperties(&employee1, &user) + + employee2 := Employee{Name: "employee001", Age: 20, Role: "User", + Addr: Address{Country: "UK", ZipCode: "002"}, salary: 500} + + CopyProperties(&employee2, &user) + + fmt.Println(employee1) + fmt.Println(employee2) + + // Output: + // {user001 10 Admin {CN 001} [a b] 0} + // {user001 10 Admin {CN 001} [a b] 500} +} ``` \ No newline at end of file diff --git a/docs/convertor_zh-CN.md b/docs/convertor_zh-CN.md index 356db7c..17220b1 100644 --- a/docs/convertor_zh-CN.md +++ b/docs/convertor_zh-CN.md @@ -39,6 +39,8 @@ import ( - [EncodeByte](#EncodeByte) - [DecodeByte](#DecodeByte) - [DeepClone](#DeepClone) +- [CopyProperties](#CopyProperties) + @@ -690,4 +692,67 @@ func main() { // map[a:1 b:2] false // &{test 1 0.1 true拷贝不同结构体之间的同名字段。
+ +函数签名: + +```go +func CopyProperties[T, U any](dst T, src U) (err error) +``` + +示例: + +```go +package main + +import ( + "fmt" + "github.com/duke-git/lancet/v2/convertor" +) + +func main() { + type Address struct { + Country string + ZipCode string + } + + type User struct { + Name string + Age int + Role string + Addr Address + Hobbys []string + salary int + } + + type Employee struct { + Name string + Age int + Role string + Addr Address + Hobbys []string + salary int + } + + user := User{Name: "user001", Age: 10, Role: "Admin", Addr: Address{Country: "CN", ZipCode: "001"}, Hobbys: []string{"a", "b"}, salary: 1000} + + employee1 := Employee{} + CopyProperties(&employee1, &user) + + employee2 := Employee{Name: "employee001", Age: 20, Role: "User", + Addr: Address{Country: "UK", ZipCode: "002"}, salary: 500} + + CopyProperties(&employee2, &user) + + fmt.Println(employee1) + fmt.Println(employee2) + + // Output: + // {user001 10 Admin {CN 001} [a b] 0} + // {user001 10 Admin {CN 001} [a b] 500} +} ``` \ No newline at end of file