2 unstable releases

0.3.0 Dec 27, 2023
0.2.0 Dec 26, 2023

#2160 in Rust patterns

Download history 17/week @ 2024-03-09 4/week @ 2024-03-16 2/week @ 2024-03-23 42/week @ 2024-03-30 57/week @ 2024-04-06 90/week @ 2024-04-13 67/week @ 2024-04-20 13/week @ 2024-04-27 2/week @ 2024-05-04 4/week @ 2024-05-11 23/week @ 2024-05-18 16/week @ 2024-05-25 26/week @ 2024-06-01 13/week @ 2024-06-08 22/week @ 2024-06-15 14/week @ 2024-06-22

77 downloads per month

MIT/Apache

17KB
215 lines

Merge2

Crate API

Provides Merge trait that can be used to merge structs into single by it's values:

trait Merge: Sized {
    fn merge(&mut self, other: &mut Self);
}

Merge can be derived for structs:

use merge2::Merge;

#[derive(Merge)]
struct User {
    #[merge(skip)]
    pub name: &'static str,
    pub location: Option<&'static str>,
    #[merge(strategy = ::merge2::vec::append)]
    pub groups: Vec<&'static str>,
}

let mut defaults = User {
    name: "",
    location: Some("Internet"),
    groups: vec!["rust"],
};
let mut ferris = User {
    name: "Ferris",
    location: None,
    groups: vec!["mascot"],
};
ferris.merge(&mut defaults);

assert_eq!("Ferris", ferris.name);
assert_eq!(Some("Internet"), ferris.location);
assert_eq!(vec!["mascot", "rust"], ferris.groups);

A merge strategy is a function with the signature fn merge<T>(left: &mut T, right: &mut T) that merges right into left. The merge2 crate provides strategies for the most common types, but you can also define your own strategies.

The trait can be used to merge configuration from different sources: environment variables, multiple configuration files and command-line arguments, see the args.rs example.

Features

This crate has the following features:

  • derive (default): Enables the derive macro for the Merge trait using the merge_derive crate.
  • num (default): Enables the merge strategies in the num module that require the num_traits crate.
  • std (default): Enables the merge strategies for the hashmap and vec that require the standard library. If this feature is not set, merge2 is a no_std.

Based on the source code of the Merge crate

Dependencies

~175KB