本文发布于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.

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 国际」 许可协议进行许可。