douyun1860 2015-08-13 07:03
浏览 21
已采纳

为结构分配另一个结构

I have a RegistrationRequest struct:

type RegistrationRequest struct {
    Email    *string
    Email2   *string        
    Username *string
    Password *string
    Name     string
}

Where Email2 is the email value entered again to verify that what the user entered is correct.

I also have a User struct:

type User struct {
    Email    *string
    Username *string
    Password *string
    Name     string           
}

Of course, there is no need to store Email2 beyond registration.

So I have two variables: req and u - one for each struct. Is it possible to assign the req struct into to the u struct so that all the common fields will exist in the u struct?

  • 写回答

2条回答 默认 最新

  • dongshuang0011 2015-08-13 07:11
    关注

    Using simple assignment you can't because even though the fields of User are a subset of RegistrationRequest, they are completely 2 different types, and Assignability rules don't apply.

    You could write a function which uses reflection (reflect package), and would copy all the fields from req to u, but that is just ugly (and inefficient).

    Best would be to refactor your types, and RegistrationRequest could embed User.

    Doing so if you have a value of type RegistrationRequest that means you already also have a value of User:

    type User struct {
        Email    *string
        Username *string
        Password *string
        Name     string
    }
    
    type RegistrationRequest struct {
        User  // Embedding User type
        Email2 *string
    }
    
    func main() {
        req := RegistrationRequest{}
        s := "as@as.com"
        req.Email = &s
    
        s2 := "testuser"
        req.Username = &s2
    
        u := User{}
        u = req.User
        fmt.Println(*u.Username, *u.Email)
    }
    

    Output: (try it on the Go Playground)

    testuser as@as.com
    

    Also please note that since your structs contain pointers, when copying a struct, pointer values will be copied and not pointed values. I'm not sure why you need pointers here, would be best to just declare all fields to be non-pointers.

    Also note that embedding is not really a requirement, it just makes your types and their usage more smooth. User could just as well be an "ordinary" field of RequistrationRequest, e.g.:

    type RegistrationRequest struct {
        Usr User // This is just an ordinary field, not embedding
        Email2 *string
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用