Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to copy only not null fields? #26

Open
frederikhors opened this issue Nov 26, 2020 · 1 comment
Open

How to copy only not null fields? #26

frederikhors opened this issue Nov 26, 2020 · 1 comment

Comments

@frederikhors
Copy link

Is there a way to copy only the not null fields?

Example:

package main

import (
	"fmt"

	"github.com/ulule/deepcopier"
)

type Player struct {
	Firstname  string
	Username   *string
	UserDetail *UserDetail
}

type PlayerInput struct {
	Firstname  *string
	Username   *string
	UserDetail *UserDetail
}

type UserDetail struct {
	Email *string
}

func main() {
	inputFirstname := "Bob"

	input := PlayerInput{
		Firstname: &inputFirstname,
	}

	outputUsername := "BobTheBob"

	output := Player{
		Username: &outputUsername,
	}

	deepcopier.Copy(&input).To(&output)

	fmt.Printf("%#v \n", output)
}

I get:

main.Player{Firstname:"Bob", Username:(*string)(nil), UserDetail:(*main.UserDetail)(nil)}

I would:

main.Player{Firstname:"Bob", Username:"BobTheBob", UserDetail:(*main.UserDetail)(nil)}

Is this possible?

@naftulikay
Copy link

I have a similar use-case, but I'm using null.* (v4) for PATCH requests, so almost every field is null and I'd like to copy only what has changed:

type UpdateNewsRequest struct {
    Title null.String
    Description null.String
}

type News struct {
    ID uint
    Title string
    Description string
}

I'm trying to see if there is a way to use the context method to do this, and while deepcopier.Copy(&updateRequest).To(&dbModel) does not return any errors, it also does not update the fields.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants