Jay Taylor's notes

back to listing index

imdario/mergo

[web search]
Original source (github.com)
Tags: merging golang go library github.com
Clipped on: 2019-06-20

Skip to content
Mergo: merging Go structs and maps since 2013.
Branch: master
New pull request
Clone or download
Image (Asset 3/22) alt= .github Create FUNDING.yml 20 days ago testdata Fixing YAML test 2 years ago .gitignore Updated README and improved .gitignore 2 years ago .travis.yml Fix the ci for pull-requests 3 months ago CODE_OF_CONDUCT.md Create CODE_OF_CONDUCT.md 2 years ago LICENSE Mergo is alive! 6 years ago README.md Update README.md 5 months ago doc.go Recursive map merge done. 6 years ago issue17_test.go Issue #33 explained and #52 refactored 2 years ago issue23_test.go Fixing pull request #62 last year issue33_test.go Fixed typo 2 years ago issue38_test.go go fmt 2 years ago issue50_test.go fix & go fmt 2 years ago issue52_test.go Issue #33 explained and #52 refactored 2 years ago issue61_test.go Revised test for #61 last year issue64_test.go Override slices if WithOverride is specified last year issue66_test.go Don't append slice if not asked to last year issue84_test.go tests for #84 last year map.go fixThis commit closes issue #84. #84 last year merge.go Merge pull request #106 from admtnnr/master 2 months ago merge_appendslice_test.go Add an option to append slice last year merge_interface_concrete_test.go Fix merging of interface types with concrete values 3 months ago merge_test.go Protect merge with transformer from nil/invalid values last year mergo.go Look through interfaces and pointers when determining emptiness last year mergo_test.go Add a new option WithTypeCheck, which ensures that slice types are th… 2 months ago pr80_test.go Look through interfaces and pointers when determining emptiness last year pr81_test.go PR #81 merged last year

README.md

Mergo

A helper to merge structs and maps in Golang. Useful for configuration default values, avoiding messy if-statements.

Also a lovely comune (municipality) in the Province of Ancona in the Italian region of Marche.

Status

It is ready for production use. It is used in several projects by Docker, Google, The Linux Foundation, VMWare, Shopify, etc.

Image (Asset 4/22) alt=Latest release

Release v0.3.7.

Important note

Please keep in mind that in 0.3.2 Mergo changed Merge()and Map() signatures to support transformers. An optional/variadic argument has been added, so it won't break existing code.

If you were using Mergo before April 6th 2015, please check your project works as intended after updating your local copy with go get -u github.com/imdario/mergo. I apologize for any issue caused by its previous behavior and any future bug that Mergo could cause (I hope it won't!) in existing projects after the change (release 0.2.0).

Donations

If Mergo is useful to you, consider buying me a coffee, a beer or making a monthly donation so I can keep building great free software.

Image (Asset 5/22) alt=Mergo in the wild

Installation

go get github.com/imdario/mergo

// use in your .go code
import (
    "github.com/imdario/mergo"
)

Usage

You can only merge same-type structs with exported fields initialized as zero value of their type and same-types maps. Mergo won't merge unexported (private) fields but will do recursively any exported one. It won't merge empty structs value as they are not considered zero values either. Also maps will be merged recursively except for structs inside maps (because they are not addressable using Go reflection).

if err := mergo.Merge(&dst, src); err != nil {
    // ...
}

Also, you can merge overwriting values using the transformer WithOverride.

if err := mergo.Merge(&dst, src, mergo.WithOverride); err != nil {
    // ...
}

Additionally, you can map a map[string]interface{} to a struct (and otherwise, from struct to map), following the same restrictions as in Merge(). Keys are capitalized to find each corresponding exported field.

if err := mergo.Map(&dst, srcMap); err != nil {
    // ...
}

Warning: if you map a struct to map, it won't do it recursively. Don't expect Mergo to map struct members of your struct as map[string]interface{}. They will be just assigned as values.

More information and examples in godoc documentation.

Nice example

package main

import (
	"fmt"
	"github.com/imdario/mergo"
)

type Foo struct {
	A string
	B int64
}

func main() {
	src := Foo{
		A: "one",
		B: 2,
	}
	dest := Foo{
		A: "two",
	}
	mergo.Merge(&dest, src)
	fmt.Println(dest)
	// Will print
	// {two 2}
}

Note: if test are failing due missing package, please execute:

go get gopkg.in/yaml.v2

Transformers

Transformers allow to merge specific types differently than in the default behavior. In other words, now you can customize how some types are merged. For example, time.Time is a struct; it doesn't have zero value but IsZero can return true because it has fields with zero value. How can we merge a non-zero time.Time?

package main

import (
	"fmt"
	"github.com/imdario/mergo"
        "reflect"
        "time"
)

type timeTransfomer struct {
}

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() {
				isZero := dst.MethodByName("IsZero")
				result := isZero.Call([]reflect.Value{})
				if result[0].Bool() {
					dst.Set(src)
				}
			}
			return nil
		}
	}
	return nil
}

type Snapshot struct {
	Time time.Time
	// ...
}

func main() {
	src := Snapshot{time.Now()}
	dest := Snapshot{}
	mergo.Merge(&dest, src, mergo.WithTransformers(timeTransfomer{}))
	fmt.Println(dest)
	// Will print
	// { 2018-01-12 01:15:00 +0000 UTC m=+0.000000001 }
}

Contact me

If I can help you, you have an idea or you are using Mergo in your projects, don't hesitate to drop me a line (or a pull request): @im_dario

About

Written by Dario Castañé.

Top Contributors

Image (Asset 6/22) alt=License

BSD 3-Clause license, as Go language.

Image (Asset 7/22) alt=