Code Monkey home page Code Monkey logo

Comments (3)

darccio avatar darccio commented on August 22, 2024 3

Ok, I understand what is happening. As per MergeWithOverwrite's documentation:

MergeWithOverwrite will do the same as Merge except that non-empty dst attributes will be overriden by non-empty src attribute values.

As I said in my previous comment, time.Time can be semantically empty (as in IsZero() returns true) but it is a struct. Structs in Go don't have a zero value by themselves, as described in the official documentation about zero value:

When storage is allocated for a variable, either through a declaration or a call of new, or when a new value is created, either through a composite literal or a call of make, and no explicit initialization is provided, the variable or value is given a default value. Each element of such a variable or value is set to the zero value for its type: false for booleans, 0 for integers, 0.0 for floats, "" for strings, and nil for pointers, functions, interfaces, slices, channels, and maps. This initialization is done recursively, so for instance each element of an array of structs will have its fields zeroed if no value is specified.

So the overwriting behavior works as expected. It overrides one struct by another one.

The only way to solve this is using transformers, as I also said in my previous comment. I wrote some tests showing how to use transformers in your case, with Merge and MergeWithOverwrite:

type structWithTime struct {
	Birth time.Time
}

type timeTransfomer struct {
	overwrite bool
}

func (t timeTransfomer) Transformer(typ reflect.Type) func (dst, src reflect.Value) error {
	if typ == reflect.TypeOf(time.Time{}) {
		return func (dst, src reflect.Value) error {
			if dst.CanSet() {
				if t.overwrite {
					isZero := src.MethodByName("IsZero")
					result := isZero.Call([]reflect.Value{})
					if !result[0].Bool() {
						dst.Set(src)
					}
				} else {
					isZero := dst.MethodByName("IsZero")
					result := isZero.Call([]reflect.Value{})
					if result[0].Bool() {
						dst.Set(src)
					}
				}
			}
			return nil
		}
	}
	return nil
}

// Expected standard behavior: ruthless overwrite.
func TestOverwriteZeroSrcTime(t *testing.T) {
	now := time.Now()
	dst := structWithTime{now}
	src := structWithTime{}
	if err := MergeWithOverwrite(&dst, src); err != nil {
		t.FailNow()
	}
	if !dst.Birth.IsZero() {
		t.Fatalf("dst should have been overwritten: dst.Birth(%v) != now(%v)", dst.Birth, now)
	}
}

// Non standard behavior for MergeWithOverwrite: src.IsZero() == true then we don't overwrite dst.
func TestOverwriteZeroSrcTimeWithTransformer(t *testing.T) {
	now := time.Now()
	dst := structWithTime{now}
	src := structWithTime{}
	if err := MergeWithOverwrite(&dst, src, WithTransformers(timeTransfomer{true})); err != nil {
		t.FailNow()
	}
	if dst.Birth.IsZero() {
		t.Fatalf("dst should not have been overwritten: dst.Birth(%v) != now(%v)", dst.Birth, now)
	}
}

// Expected standard behavior: ruthless overwrite.
func TestOverwriteZeroDstTime(t *testing.T) {
	now := time.Now()
	dst := structWithTime{}
	src := structWithTime{now}
	if err := MergeWithOverwrite(&dst, src); err != nil {
		t.FailNow()
	}
	if dst.Birth.IsZero() {
		t.Fatalf("dst should have been overwritten: dst.Birth(%v) != zero(%v)", dst.Birth, time.Time{})
	}
}

// Expected standard behavior: dst is a struct and structs doesn't have a zero value, so we don't overwrite it.
func TestZeroDstTime(t *testing.T) {
	now := time.Now()
	dst := structWithTime{}
	src := structWithTime{now}
	if err := Merge(&dst, src); err != nil {
		t.FailNow()
	}
	if !dst.Birth.IsZero() {
		t.Fatalf("dst should not have been overwritten: dst.Birth(%v) != zero(%v)", dst.Birth, time.Time{})
	}
}

// Non standard behavior for Merge: dst.IsZero() == true then we overwrite dst.
func TestZeroDstTimeWithTransformer(t *testing.T) {
	now := time.Now()
	dst := structWithTime{}
	src := structWithTime{now}
	if err := Merge(&dst, src, WithTransformers(timeTransfomer{})); err != nil {
		t.FailNow()
	}
	if dst.Birth.IsZero() {
		t.Fatalf("dst should have been overwritten: dst.Birth(%v) != now(%v)", dst.Birth, now)
	}
}

from mergo.

darccio avatar darccio commented on August 22, 2024

Updated: I understood wrongly your issue and my assumptions were also wrong. I'm checking this.

This is expected behavior. Mergo checks for zero values of basic types. time.Time isn't a basic type but a struct. Although semantically time.Time{} is empty, it isn't an empty (zero value) struct because it has non-zero value fields.

Changing this behavior would mean to support every possible way to check if a struct is semantically empty, calling specific functions. It could work for stdlib's non-basic types but it won't scale.

So, there is no hope? Of course there is :) I just merged PR #49 that adds transformers. Transformers allow to merge specific types differently that the default. I'm just getting used to it (it was implemented by @vdemeester from Docker) and I think it fits right in your case.

from mergo.

diego-aslz avatar diego-aslz commented on August 22, 2024

Thank you so much @imdario for the explanation. I'm gonna use the Transformer approach.

from mergo.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.