用另一个结构分配结构 [英] Assign struct with another struct

查看:31
本文介绍了用另一个结构分配结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 RegistrationRequest 结构:

I have a RegistrationRequest struct:

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

其中 Email2 是再次输入的电子邮件值,以验证用户输入的内容是否正确.

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

我也有一个用户结构:

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

当然,除了注册之外,无需存储Email2.

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

所以我有两个变量:requ - 每个结构一个.是否可以将 req 结构分配给 u 结构,以便所有公共字段都存在于 u 结构中?

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?

推荐答案

使用简单的assignment你不能,因为即使 User 的字段是 RegistrationRequest 的子集,它们也是完全不同的 2 种类型,并且 可分配性 规则不适用.

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.

您可以编写一个使用反射的函数(reflect 包),并将所有字段从 req 复制到 u,但这只是丑陋(而且效率低下).

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).

最好重构您的类型,RegistrationRequest 可以嵌入 用户.

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

如果你有一个 RegistrationRequest 类型的值,那么你已经有一个 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)
}

输出:(在 Go Playground 上试试)

Output: (try it on the Go Playground)

testuser as@as.com

另请注意,由于您的结构包含指针,因此在复制 struct 时,将复制指针值而不是指向值.我不确定您为什么需要在这里使用指针,最好将所有字段声明为非指针.

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.

另请注意,嵌入并不是真正的要求,它只是使您的类型及其使用更加流畅.User 也可以是 RequistrationRequest 的普通"字段,例如:

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
}

这篇关于用另一个结构分配结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆