在 Nix 中,您可以使用
//
来合并两个集合,并用右侧的属性替换左侧的属性(如果它们是双倍的)。在这个例子中:
let
set_one = {
nested_set = {
some_value_that_will_be_lost = "some forgotten value";
some_attribute = "some value";
};
};
set_two = {
nested_set = {
some_attribute = "some other value";
};
};
in ( set_one // set_two )
将导致:
{
nested_set = {
some_attribute = "some other value";
};
}
当我期待时:
{
nested_set = {
some_value_that_will_be_lost = "some forgotten value";
some_attribute = "some other value";
};
}
我尝试看看lib是否有任何有用的功能,我发现了
lib.modules.mergeModules
,并尝试了:
let
lib = (import <nixpkgs> { }).pkgs.lib;
set_one = {
nested_set = {
some_value_that_will_be_lost = "some forgotten value";
some_attribute = "some value";
};
};
set_two = {
nested_set = {
some_attribute = "some other value";
};
};
in ( lib.modules.mergeModules set_one set_two )
但是该模块已被废弃,并且只会导致错误。
问题是我希望无论设置是什么,实现都能工作。有没有一种方法可以做到这一点,您知道如何在不知道其内容的情况下深度/递归地合并两个集合?
参见 lib.attrsets.recursiveUpdate
let
pkgs = import <nixpkgs> {};
lib = pkgs.lib;
set_one = {
nested_set = {
some_value_that_will_be_lost = "some forgotten value";
some_attribute = "some value";
};
};
set_two = {
nested_set = {
some_attribute = "some other value";
};
};
in
lib.recursiveUpdate set_one set_two
评估为
{ nested_set = { some_attribute = "some other value"; some_value_that_will_be_lost = "some forgotten value"; }; }