Skip to content

copier

Repository open source: jinzhu/copier: Copier for golang, copy value from struct to struct and more (github.com)

Indirizzo documentazione: jinzhu/copier: Copier for golang, copy value from struct to struct and more (github.com)

copier è una libreria per la copia di tipi in Go, utilizzata principalmente per la conversione tra struct. L'autore è lo stesso di gorm. Ha le seguenti caratteristiche

  • Copia profonda
  • Copia campi con lo stesso nome
  • Copia slice
  • Copia map
  • Copia metodi

Poiché la copia di copier si basa sulla riflessione, ci sarà una certa perdita di prestazioni. Generalmente le librerie di copia di tipo si dividono in due categorie: quelle basate sulla riflessione come copier, e quelle basate sulla generazione di codice che generano codice di conversione di tipo, questo metodo non causa perdita di prestazioni. Una libreria simile è jmattheis/goverter.

Installazione

sh
 go get github.com/jinzhu/copier

Utilizzo

Questa libreria è molto semplice da usare ma estremamente pratica. Espone solo due funzioni, una è copier.Copy.

go
func Copy(toValue interface{}, fromValue interface{}) (err error)

L'altra è copier.CopyWithOption, quest'ultima consente di configurare il comportamento di copia, per impostazione predefinita non esegue una copia profonda.

go
type Option struct {
  IgnoreEmpty   bool
  CaseSensitive bool
  DeepCopy      bool
  FieldNameMapping []FieldNameMapping
}

func CopyWithOption(toValue interface{}, fromValue interface{}, opt Option) (err error)

Di seguito è riportato un esempio di conversione tra struct di tipi diversi, dove User e Student sono due tipi completamente diversi senza alcuna relazione.

go
type User struct {
  Id   string
  Name string
  // Ignora questo campo quando è la struct di destinazione
  Address string `copier:"-"`
}

type Student struct {
  // Specifica il nome del campo
  StudentId   string `copier:"Id"`
  StudentName string `copier:"Name"`
  Address     string
  School      string
  Class       string
}

func main() {
  student := Student{
    StudentId:   "123",
    StudentName: "jack",
    Address:     "usa",
    School:      "MIT",
    Class:       "AI",
  }
  user := User{}
  if err := copier.Copy(&user, &student); err != nil {
    panic(err)
  }
  fmt.Printf("%+v\n", student)
  fmt.Printf("%+v\n", user)
}

Output

{StudentId:123 StudentName:jack Address:usa School:MIT Class:AI}
{Id:123 Name:jack Address:}

Di seguito la copia di slice

go
func main() {
  student := []Student{
    {
      StudentId:   "123",
      StudentName: "jack",
      Address:     "usa",
      School:      "MIT",
      Class:       "AI",
    },
    {
      StudentId:   "123",
      StudentName: "jack",
      Address:     "usa",
      School:      "MIT",
      Class:       "AI",
    },
  }

  var user []User
  if err := copier.Copy(&user, &student); err != nil {
    panic(err)
  }
  fmt.Printf("%+v\n", student)
  fmt.Printf("%+v\n", user)
}

Output

[{StudentId:123 StudentName:jack Address:usa School:MIT Class:AI} {StudentId:123 StudentName:jack Address:usa School:MIT Class:AI}]
[{Id:123 Name:jack Address:} {Id:123 Name:jack Address:}]

Copia di map

go
type User struct {
  Id   string
  Name string
  // Ignora questo campo quando è la struct di destinazione
  Address string `copier:"-"`
}

type Student struct {
  // Specifica il nome del campo
  StudentId   string `copier:"Id"`
  StudentName string `copier:"Name"`
  Address     string
  School      string
  Class       string
}

func main() {
  student := Student{
    StudentId:   "123",
    StudentName: "jack",
    Address:     "usa",
    School:      "MIT",
    Class:       "AI",
  }

  src := make(map[string]Student)
  src["a"] = student
  src["b"] = student

  dest := make(map[string]User)

  if err := copier.Copy(&dest, &src); err != nil {
    panic(err)
  }
  fmt.Printf("%+v\n", src)
  fmt.Printf("%+v\n", dest)
}

Output

map[a:{StudentId:123 StudentName:jack Address:usa School:MIT Class:AI} b:{StudentId:123 StudentName:jack Address:usa School:MIT Class:AI}]
map[a:{Id:123 Name:jack Address:} b:{Id:123 Name:jack Address:}]

Personalizzazione

È anche possibile personalizzare i metodi di conversione, basta passare copier.TypeConverter

go
type TypeConverter struct {
  SrcType interface{}
  DstType interface{}
  Fn      func(src interface{}) (dst interface{}, err error)
}

Come mostrato di seguito

go
type User struct {
  Id   string
  Name string
  // Ignora questo campo quando è la struct di destinazione
  Address string `copier:"-"`
}

type Student struct {
  // Specifica il nome del campo
  StudentId   string `copier:"Id"`
  StudentName string `copier:"Name"`
  Address     string
  School      string
  Class       string
}

func main() {
  student := Student{
    StudentId:   "123",
    StudentName: "jack",
    Address:     "usa",
    School:      "MIT",
    Class:       "AI",
  }

  src := make(map[string]Student)
  src["a"] = student
  src["b"] = student

  dest := make(map[string]User)

  if err := copier.CopyWithOption(&dest, &src, copier.Option{
    IgnoreEmpty:   false,
    CaseSensitive: false,
    DeepCopy:      false,
    Converters: []copier.TypeConverter{
      {
        SrcType: Student{},
        DstType: User{},
        Fn: func(src interface{}) (dst interface{}, err error) {
          s, ok := src.(Student)
          if !ok {
            return User{}, errors.New("tipo errato")
          }
          return User{
            Id: s.StudentId,
          }, nil
        },
      },
    },
    FieldNameMapping: nil,
  }); err != nil {
    panic(err)
  }
  fmt.Printf("%+v\n", src)
  fmt.Printf("%+v\n", dest)
}

Output

map[a:{StudentId:123 StudentName:jack Address:usa School:MIT Class:AI} b:{StudentId:123 StudentName:jack Address:usa School:MIT Class:AI}]
map[a:{Id:123 Name: Address:} b:{Id:123 Name: Address:}]

Golang by www.golangdev.cn edit