deepcopier icon indicating copy to clipboard operation
deepcopier copied to clipboard

How to copy only not null fields?

Open frederikhors opened this issue 4 years ago • 1 comments

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?

frederikhors avatar Nov 26 '20 00:11 frederikhors

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.

naftulikay avatar Aug 28 '21 21:08 naftulikay