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
}