且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用另一个结构分配结构

更新时间:2023-02-11 18:02:43

使用简单的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
}