• Stars
    star
    2,876
  • Rank 15,774 (Top 0.4 %)
  • Language
    Go
  • License
    BSD 3-Clause "New...
  • Created over 11 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Mergo: merging Go structs and maps since 2013

Mergo

GitHub release GoCard Test status OpenSSF Scorecard OpenSSF Best Practices Coverage status Sourcegraph FOSSA status

GoDoc Become my sponsor Tidelift

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

Mergo merges same-type structs and maps by setting default values in zero-value fields. Mergo won't merge unexported (private) fields. It will do recursively any exported one. It also won't merge structs inside maps (because they are not addressable using Go reflection).

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

Status

Mergo is stable and frozen, ready for production. Check a short list of the projects using at large scale it here.

No new features are accepted. They will be considered for a future v2 that improves the implementation and fixes bugs for corner cases.

Important notes

1.0.0

In 1.0.0 Mergo moves to a vanity URL dario.cat/mergo. No more v1 versions will be released.

If the vanity URL is causing issues in your project due to a dependency pulling Mergo - it isn't a direct dependency in your project - it is recommended to use replace to pin the version to the last one with the old import URL:

replace github.com/imdario/mergo => github.com/imdario/mergo v0.3.16

0.3.9

Please keep in mind that a problematic PR broke 0.3.9. I reverted it in 0.3.10, and I consider it stable but not bug-free. Also, this version adds support for go modules.

Keep in mind that in 0.3.2, Mergo changed Merge()and Map() signatures to support transformers. I added an optional/variadic argument so that it won't break the 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 dario.cat/mergo. I apologize for any issue caused by its previous behavior and any future bug that Mergo could cause 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 to allow me to keep building great free software. 😍

Donate using Liberapay Become my sponsor

Mergo in the wild

Mergo is used by thousands of projects, including:

Install

go get dario.cat/mergo

// use in your .go code
import (
    "dario.cat/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 zero values too. 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 {
    // ...
}

If you need to override pointers, so the source pointer's value is assigned to the destination's pointer, you must use WithoutDereference:

package main

import (
	"fmt"

	"dario.cat/mergo"
)

type Foo struct {
	A *string
	B int64
}

func main() {
	first := "first"
	second := "second"
	src := Foo{
		A: &first,
		B: 2,
	}

	dest := Foo{
		A: &second,
		B: 1,
	}

	mergo.Merge(&dest, src, mergo.WithOverride, mergo.WithoutDereference)
}

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.

Here is a nice example:

package main

import (
	"fmt"
	"dario.cat/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.v3

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"
	"dario.cat/mergo"
    "reflect"
    "time"
)

type timeTransformer struct {
}

func (t timeTransformer) 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(timeTransformer{}))
	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ñé.

License

BSD 3-Clause license, as Go language.

FOSSA Status

More Repositories

1

zas

Most simple static website generator in Golang.
Go
194
star
2

go-ulid

Universally Unique Lexicographically Sortable Identifier (ULID) in Go - Please use https://github.com/oklog/ulid
Go
31
star
3

medeina

Go HTTP routing tree based on HttpRouter. Inspired by Roda and Cuba.
Go
19
star
4

gluo

Write your Go net/http server once, deploy it everywhere (on-premise & AWS Lambda supported)
Go
14
star
5

go-html-transform

Unofficial mirror of go-html-transform project: an html5 parser and CSS selector based html scraping and transformation library.
Go
7
star
6

xdr

XDR (External Data Representation; RFC 4506) pure Go implementation
Go
5
star
7

BOFHchan

Go
4
star
8

gonban

Go native webview wrapper for Kanelm (kanban board built with Elm)
Go
3
star
9

pipar

Open Data scrapper of political parties registries. Currently only for Ministry of Interior of Spain registry. Open to other countries!
Ruby
3
star
10

darccio

My personal site (created with Zas)
HTML
2
star
11

sobtec2016

Talk about technological status of Catalan cities at I Congrés de Sobirania Tecnològica [2016-02-20 Completed]
JavaScript
2
star
12

gildo

Federated discovery and recommendation for decentralized social networks (incubation)
Python
2
star
13

atkvaedi

Atkvaedi simple voting
Java
1
star
14

estonia2019

HTML
1
star
15

qantiqa

Decentralized microblogging - Final degree project (2010; not maintained)
JavaScript
1
star
16

gotpher

A little gopher companion for andOTP
Go
1
star
17

fopts-ng

Experimental repo to explore improved functional options' implementations
Go
1
star
18

caddy2-locale

Go
1
star
19

registro

Authentication REST API over LDAP
Go
1
star
20

accent

Pick unused Pantone colors from a reference colors list.
JavaScript
1
star
21

errors

Go
1
star