本文发布于Cylon的收藏册,转载请著名原文链接~

question: How use golang Copy one struct to another where structs have same members and different types

此时需要的库

  • github.com/ulule/deepcopier
  • github.com/jinzhu/copier

E.g.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package main

import (
   "fmt"

   "github.com/ulule/deepcopier"
)

// Model
type User struct {
    // Basic string field
    Name  string
    // Deepcopier supports https://golang.org/pkg/database/sql/driver/#Valuer
    Email sql.NullString
}

func (u *User) MethodThatTakesContext(ctx map[string]interface{}) string {
    // do whatever you want
    return"hello from this method"
}

// Resource
type UserResource struct {
    //copy from field"Name"
    DisplayName            string `deepcopier:"field:Name"`
    //this will be skipped in copy
    SkipMe                 string `deepcopier:"skip"`
    //this should call method named MethodThatTakesContext
    MethodThatTakesContext string `deepcopier:"context"`
    Email                  string `deepcopier:"force"`

}

func main() {
    user := &User{
        Name:"gilles",
        Email: sql.NullString{
            Valid: true,
            String:"gilles@example.com",
        },
    }

    resource := &UserResource{}

    deepcopier.Copy(user).To(resource)
    //copied from User's Name field
    fmt.Println(resource.DisplayName)//output: gilles
    fmt.Println(resource.Email) //output: gilles@example.com
    fmt.Println(resource.MethodThatTakesContext) //output: hello from this method
}

Reference

copy different struct

本文发布于Cylon的收藏册,转载请著名原文链接~

链接:https://www.oomkill.com/2021/10/golib-deepcopier/

版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」 许可协议进行许可。