mergo

package module
v0.3.13 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 3, 2022 License: BSD-3-Clause Imports: 5 Imported by: 1

README

Mergo

GoDoc GitHub release GoCard Build Status Coverage Status Sourcegraph FOSSA Status [![Become my sponsor][15]][16]

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

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

Important note

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 gomodules.xyz/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. 😍

Buy Me a Coffee at ko-fi.com Donate using Liberapay Become my sponsor

Mergo in the wild

Install

go get gomodules.xyz/mergo

// use in your .go code
import (
    "gomodules.xyz/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 {
    // ...
}

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"
	"gomodules.xyz/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"
	"gomodules.xyz/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

Documentation

Overview

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).

Status

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

Important note

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

Keep in mind that in 0.3.2, Mergo changed Merge() and Map() signatures to support transformers. We 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 gomodules.xyz/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).

Install

Do your usual installation procedure:

go get gomodules.xyz/mergo

// use in your .go code
import (
    "gomodules.xyz/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 {
	// ...
}

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"
	"gomodules.xyz/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}
}

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"
	"gomodules.xyz/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): https://twitter.com/im_dario

About

Written by Dario Castañé: https://da.rio.hn

License

BSD 3-Clause license, as Go language.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNilArguments                = errors.New("src and dst must not be nil")
	ErrDifferentArgumentsTypes     = errors.New("src and dst must be of same type")
	ErrNotSupported                = errors.New("only structs, maps, and slices are supported")
	ErrExpectedMapAsDestination    = errors.New("dst was expected to be a map")
	ErrExpectedStructAsDestination = errors.New("dst was expected to be a struct")
	ErrNonPointerAgument           = errors.New("dst must be a pointer")
)

Errors reported by Mergo when it finds invalid arguments.

Functions

func Map

func Map(dst, src interface{}, opts ...func(*Config)) error

Map sets fields' values in dst from src. src can be a map with string keys or a struct. dst must be the opposite: if src is a map, dst must be a valid pointer to struct. If src is a struct, dst must be map[string]interface{}. It won't merge unexported (private) fields and will do recursively any exported field. If dst is a map, keys will be src fields' names in lower camel case. Missing key in src that doesn't match a field in dst will be skipped. This doesn't apply if dst is a map. This is separated method from Merge because it is cleaner and it keeps sane semantics: merging equal types, mapping different (restricted) types.

func MapWithOverwrite

func MapWithOverwrite(dst, src interface{}, opts ...func(*Config)) error

MapWithOverwrite will do the same as Map except that non-empty dst attributes will be overridden by non-empty src attribute values. Deprecated: Use Map(…) with WithOverride

func Merge

func Merge(dst, src interface{}, opts ...func(*Config)) error

Merge will fill any empty for value type attributes on the dst struct using corresponding src attributes if they themselves are not empty. dst and src must be valid same-type structs and dst must be a pointer to struct. It won't merge unexported (private) fields and will do recursively any exported field.

func MergeWithOverwrite

func MergeWithOverwrite(dst, src interface{}, opts ...func(*Config)) error

MergeWithOverwrite will do the same as Merge except that non-empty dst attributes will be overridden by non-empty src attribute values. Deprecated: use Merge(…) with WithOverride

func WithAppendSlice added in v0.3.4

func WithAppendSlice(config *Config)

WithAppendSlice will make merge append slices instead of overwriting it.

func WithOverride

func WithOverride(config *Config)

WithOverride will make merge override non-empty dst attributes with non-empty src attributes values.

func WithOverrideEmptySlice added in v0.3.8

func WithOverrideEmptySlice(config *Config)

WithOverrideEmptySlice will make merge override empty dst slice with empty src slice.

func WithOverwriteWithEmptyValue added in v0.3.9

func WithOverwriteWithEmptyValue(config *Config)

WithOverwriteWithEmptyValue will make merge override non empty dst attributes with empty src attributes values.

func WithSliceDeepCopy added in v0.3.13

func WithSliceDeepCopy(config *Config)

WithSliceDeepCopy will merge slice element one by one with Overwrite flag.

func WithTransformers

func WithTransformers(transformers Transformers) func(*Config)

WithTransformers adds transformers to merge, allowing to customize the merging of some types.

func WithTypeCheck added in v0.3.8

func WithTypeCheck(config *Config)

WithTypeCheck will make merge check types while overwriting it (must be used with WithOverride).

Types

type Config

type Config struct {
	Overwrite    bool
	AppendSlice  bool
	TypeCheck    bool
	Transformers Transformers
	// contains filtered or unexported fields
}

type Transformers

type Transformers interface {
	Transformer(reflect.Type) func(dst, src reflect.Value) error
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL