Top Related Projects
Quick Overview
Mergo is a Go library that provides deep merging functionality for structs and maps. It allows developers to merge two structures, filling in missing fields in one structure with values from another, making it particularly useful for configuration management and data manipulation tasks in Go applications.
Pros
- Supports deep merging of nested structures and maps
- Offers flexible merging options with customizable behavior
- Well-documented and easy to integrate into existing Go projects
- Actively maintained with regular updates and improvements
Cons
- Limited to merging Go structs and maps, not applicable for other data types
- May have performance overhead for very large or complex structures
- Requires careful consideration of merge options to avoid unintended results
- Learning curve for advanced usage and custom merge strategies
Code Examples
- Basic merging of structs:
type Person struct {
Name string
Age int
}
src := Person{Name: "John", Age: 30}
dst := Person{Name: "Jane"}
if err := mergo.Merge(&dst, src); err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", dst) // Output: {Name:Jane Age:30}
- Merging maps:
src := map[string]interface{}{"name": "John", "age": 30}
dst := map[string]interface{}{"name": "Jane", "city": "New York"}
if err := mergo.Merge(&dst, src); err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", dst) // Output: map[age:30 city:New York name:Jane]
- Using merge options:
type Config struct {
Debug bool
Port int
}
src := Config{Debug: true, Port: 8080}
dst := Config{Port: 9000}
if err := mergo.Merge(&dst, src, mergo.WithOverride); err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", dst) // Output: {Debug:true Port:8080}
Getting Started
To use Mergo in your Go project, follow these steps:
-
Install the library:
go get github.com/imdario/mergo
-
Import the library in your Go code:
import "github.com/imdario/mergo"
-
Use the
Merge
function to merge structs or maps:if err := mergo.Merge(&destination, source); err != nil { // Handle error }
For more advanced usage and options, refer to the project's documentation on GitHub.
Competitor Comparisons
Mergo: merging Go structs and maps since 2013
Pros of mergo
- More active development and maintenance
- Better documentation and examples
- Wider community adoption and support
Cons of mergo
- Slightly larger codebase
- May have more dependencies
- Potentially higher learning curve for new users
Code Comparison
mergo:
err := mergo.Merge(&dst, src, mergo.WithOverride)
mergo>:
err := mergo.Merge(&dst, src)
Both repositories provide similar functionality for merging Go structs, maps, and slices. The main difference in usage is that mergo offers more configuration options through additional parameters, while mergo> has a simpler API.
mergo is generally considered the more feature-rich and actively maintained project, with regular updates and improvements. It offers more flexibility in handling complex merge scenarios and has better documentation.
mergo>, on the other hand, is a simpler alternative that may be easier to use for basic merge operations. However, it lacks some of the advanced features and customization options provided by mergo.
Overall, mergo is recommended for projects requiring more advanced merging capabilities and ongoing support, while mergo> might be suitable for simpler use cases or projects with minimal merge requirements.
Copier for golang, copy value from struct to struct and more
Pros of copier
- Supports deep copying of structs, maps, and slices
- Handles embedded fields and unexported fields
- Provides options for ignoring empty fields and zero values
Cons of copier
- Less flexible for merging complex nested structures
- May have performance overhead for large, deeply nested objects
- Limited support for custom merge strategies
Code Comparison
copier:
type User struct {
Name string
Age int
}
user := User{Name: "John", Age: 30}
copier.Copy(&newUser, user)
mergo:
type User struct {
Name string
Age int
}
user := User{Name: "John", Age: 30}
mergo.Merge(&newUser, user)
Key Differences
- copier focuses on deep copying of structs and slices, while mergo specializes in merging maps and structs
- mergo offers more flexibility for custom merge behaviors and transformations
- copier provides simpler usage for straightforward copying scenarios
- mergo has better support for handling conflicts and overwriting fields
Use Cases
- Choose copier for simple deep copying of structs and slices
- Opt for mergo when dealing with complex merging scenarios or requiring custom merge strategies
- Consider copier for projects prioritizing ease of use and straightforward copying
- Select mergo for applications needing fine-grained control over merging behavior
Utilities for Go structs
Pros of structs
- Focuses specifically on struct manipulation and reflection
- Provides a wide range of struct-related operations (e.g., mapping, filling, naming)
- Lightweight and easy to use for struct-specific tasks
Cons of structs
- Limited to struct operations, not general-purpose merging
- Lacks advanced merging capabilities for complex nested structures
- May require additional code for deep copying or complex transformations
Code Comparison
structs:
s := structs.New(person)
fields := s.Fields()
names := s.Names()
mergo:
dst := &SomeStruct{}
src := AnotherStruct{}
mergo.Merge(dst, src)
Summary
structs is ideal for struct-specific operations and reflection, offering a focused set of tools for working with Go structs. It excels in tasks like field mapping, naming, and struct-to-map conversions.
mergo, on the other hand, is more versatile for general-purpose merging of various data structures, including nested ones. It's particularly useful for complex merging scenarios and configuration management.
Choose structs for struct-centric tasks and lightweight operations, while mergo is better suited for advanced merging and deep copying across different types of structures.
safe and easy casting from one type to another in Go
Pros of Cast
- Focuses on type conversion and provides a wide range of casting functions
- Offers more flexibility in handling different data types and formats
- Includes utilities for parsing environment variables and command-line flags
Cons of Cast
- Limited to type conversion and doesn't offer merging capabilities
- May require additional libraries for more complex data manipulation tasks
- Less suitable for deep struct merging or complex configuration management
Code Comparison
Cast:
value, err := cast.ToInt("123")
duration, err := cast.ToDuration("1h30m")
slice, err := cast.ToStringSlice("a,b,c")
Mergo:
err := mergo.Merge(&dst, src)
err := mergo.MergeWithOverwrite(&dst, src)
err := mergo.Map(&dst, src, mergo.WithOverride)
Key Differences
- Cast focuses on type conversion and parsing, while Mergo specializes in merging structs and maps
- Mergo is more suitable for configuration management and deep merging of complex data structures
- Cast provides a broader range of conversion functions for various data types
- Mergo offers more control over the merging process with customizable options
Use Cases
Cast is ideal for:
- Converting between different data types
- Parsing environment variables and command-line flags
- Handling type conversions in web applications
Mergo is better suited for:
- Merging configuration files
- Updating nested structs or maps
- Implementing override mechanisms in complex data structures
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Mergo
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. :heart_eyes:
Mergo in the wild
Mergo is used by thousands of projects, including:
- containerd/containerd
- datadog/datadog-agent
- docker/cli/
- goreleaser/goreleaser
- go-micro/go-micro
- grafana/loki
- kubernetes/kubernetes
- masterminds/sprig
- moby/moby
- slackhq/nebula
- volcano-sh/volcano
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.
Top Related Projects
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot