Expand description
Provides Merge
, a trait for objects that can be merged.
§Usage
trait Merge {
fn merge(&mut self, other: Self);
}
The Merge
trait can be used to merge two objects of the same type into one. The intended
use case is merging configuration from different sources, for example environment variables,
multiple configuration files and command-line arguments, see the args.rs
example.
This crate does not provide any Merge
implementations, but Merge
can be derived for
structs. When deriving the Merge
trait for a struct, you can provide custom merge strategies
for the fields that don’t implement Merge
. A merge strategy is a function with the signature
fn merge<T>(left: &mut T, right: T)
that merges right
into left
. The submodules of this
crate provide strategies for the most common types, but you can also define your own
strategies.
§Features
This crate has the following features:
derive
(default): Enables the derive macro for theMerge
trait using themerge_derive
crate.num
(default): Enables the merge strategies in thenum
module that require thenum_traits
crate.std
(default): Enables the merge strategies in thehashmap
andvec
modules that require the standard library. If this feature is not set,merge
is ano_std
library.
§Example
use merge::Merge;
#[derive(Merge)]
struct User {
// Fields with the skip attribute are skipped by Merge
#[merge(skip)]
pub name: &'static str,
// The strategy attribute is used to customize the merge behavior
#[merge(strategy = merge::option::overwrite_none)]
pub location: Option<&'static str>,
#[merge(strategy = merge::vec::append)]
pub groups: Vec<&'static str>,
}
let defaults = User {
name: "",
location: Some("Internet"),
groups: vec!["rust"],
};
let mut ferris = User {
name: "Ferris",
location: None,
groups: vec!["mascot"],
};
ferris.merge(defaults);
assert_eq!("Ferris", ferris.name);
assert_eq!(Some("Internet"), ferris.location);
assert_eq!(vec!["mascot", "rust"], ferris.groups);
Modules§
- bool
- Merge strategies for boolean types.
- hashmap
- Merge strategies for hash maps.
- num
- Merge strategies for numeric types.
- option
- Merge strategies for
Option
- ord
- Merge strategies for types that form a total order.
- vec
- Merge strategies for vectors.
Traits§
- Merge
- A trait for objects that can be merged.