From da648b4707fb1d8fd6a9679669d2eb36a5f0832c Mon Sep 17 00:00:00 2001 From: Vincent Ambo Date: Tue, 10 Oct 2023 13:54:16 +0300 Subject: docs(nix-1p): add section about the merge operator Without the examples, some behaviour of the merge operator might not be clear from the previous description. Due to how pervasively the operator is used, I think it warrants a separate section. This fixes https://github.com/tazjin/nix-1p/issues/16 Change-Id: Iecba5f1cb749bef0a4987b3fc5642832a92c18d5 Reviewed-on: https://cl.tvl.fyi/c/depot/+/9599 Autosubmit: tazjin Tested-by: BuildkiteCI Reviewed-by: flokli --- nix/nix-1p/README.md | 34 ++++++++++++++++++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) (limited to 'nix') diff --git a/nix/nix-1p/README.md b/nix/nix-1p/README.md index 72297a5551..5d2dce83bf 100644 --- a/nix/nix-1p/README.md +++ b/nix/nix-1p/README.md @@ -19,6 +19,7 @@ and entering code snippets there. - [Language constructs](#language-constructs) - [Primitives / literals](#primitives--literals) - [Operators](#operators) + - [`//` (merge) operator](#-merge-operator) - [Variable bindings](#variable-bindings) - [Functions](#functions) - [Multiple arguments (currying)](#multiple-arguments-currying) @@ -113,8 +114,6 @@ rec { a = 15; b = a * 2; } Nix has several operators, most of which are unsurprising: -Make sure to understand the `//`-operator, as it is used quite a lot and is -probably the least familiar one. | Syntax | Description | |---------------------------|-----------------------------------------------------------------------------| | `+`, `-`, `*`, `/` | Numerical operations | @@ -131,6 +130,37 @@ probably the least familiar one. | `left // right` | Merge `left` & `right` attribute sets, with the right set taking precedence | +### `//` (merge) operator + +The `//`-operator is used pervasively in Nix code. You should familiarise +yourself with it, as it is likely also the least familiar one. + +It merges the left and right attribute sets given to it: + +```nix +{ a = 1; } // { b = 2; } + +# yields { a = 1; b = 2; } +``` + +Values from the right side take precedence: + +```nix +{ a = "left"; } // { a = "right"; } + +# yields { a = "right"; } +``` + +The merge operator does *not* recursively merge attribute sets; + +```nix +{ a = { b = 1; }; } // { a = { c = 2; }; } + +# yields { a = { c = 2; }; } +``` + +Helper functions for recursive merging exist in the [`lib` library](#pkgslib). + ## Variable bindings Bindings in Nix are introduced locally via `let` expressions, which make some -- cgit 1.4.1