duanche2007 2018-12-05 08:50
浏览 2094
已采纳

在Golang中将值从一个结构复制到另一个

I've two structs:

type UpdateableUser struct {
    FirstName string
    LastName string
    Email string
    Tlm float64
    Dob time.Time
}

type User struct {
    Id string
    FirstName string
    LastName string
    Email string
    DOB time.Time
    Tlm float64
    created time.Time
    updated time.Time
}

Through a binder I bind request data to the updateableUser struct, therefore I might have an updateableUser with only one "real" value, like uu here:

uu := UpdateableUser{Lastname: "Smith"}

Now I want to set only the not "emtpy" values from UpdateableUser to User. Can you please give me a hint or more?

  • 写回答

1条回答 默认 最新

  • douhuiyan2772 2018-12-05 09:15
    关注

    I would recommend embedding the Updateable struct into the larger struct:

    type UpdateableUser struct {
        FirstName string
        LastName  string
        Email     string
        Tlm       float64
        Dob       time.Time
    }
    
    type User struct {
        UpdateableUser
        ID      string
        created time.Time
       updated time.Time
    }
    
    func (u *User) UpdateFrom(src *UpdateableUser) {
        if src.FirstName != "" {
            u.FirstName = src.FirstName
        }
        if src.LastName != "" {
            u.LastName = src.LastName
        }
        // ... And other properties. Tedious, but simple and avoids Reflection
    }
    

    This allows you to use UpdateableUser as an interface to make it explicit which properties can be updated.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 腾讯IOA系统怎么在文件夹里修改办公网络的连接
  • ¥15 filenotfounderror:文件是存在的,权限也给了,但还一直报错
  • ¥15 MATLAB和mosek的求解问题
  • ¥20 修改中兴光猫sn的时候提示失败
  • ¥15 java大作业爬取网页
  • ¥15 怎么获取欧易的btc永续合约和交割合约的5m级的历史数据用来回测套利策略?
  • ¥15 有没有办法利用libusb读取usb设备数据
  • ¥15 为什么openeluer里面按不了python3呢?
  • ¥15 关于#matlab#的问题:训练序列与输入层维度不一样
  • ¥15 关于Ubuntu20.04.3LTS遇到的问题:在安装完CUDA驱动后,电脑会进入卡死的情况,但可以通过键盘按键进入安全重启,但重启完又会进入该情况!