From 2a098e081b92ce20d320a3bc3491594984d26450 Mon Sep 17 00:00:00 2001 From: Vincent Ambo Date: Sun, 14 Nov 2021 15:47:24 +0300 Subject: Document binding of attribute set arguments using '@' First and foremost this is being added because it was lacking, and nix-1p strives to have fairly complete coverage of all useful features. Additionally, as pointed out by @nixinator in #6 there is some surprising behaviour around how default arguments work in combination with '@' and I thought this was worth noting. --- nix/nix-1p/README.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/nix/nix-1p/README.md b/nix/nix-1p/README.md index c8f4b328fa..6cc37634ed 100644 --- a/nix/nix-1p/README.md +++ b/nix/nix-1p/README.md @@ -234,6 +234,33 @@ let greeter = { name, age, ... }: "${name} is ${toString age} years old"; in greeter person # ... but the call works due to the ellipsis. ``` +Nix also supports binding the whole set of passed in attributes to a +parameter using the `@` syntax: + +```nix +let func = { name, age, ... }@args: builtins.attrNames args; +in func { + name = "Slartibartfast"; + age = 42; + email = "slartibartfast@magrath.ea"; +} + +# yields: [ "age" "email" "name" ] +``` + +**Warning:** Combining the `@` syntax with default arguments can lead +to surprising behaviour, as the passed attributes are bound verbatim. +This means that defaulted arguments are not included in the bound +attribute set: + +```nix +({ a ? 1, b }@args: args.a) { b = 1; } +# throws: error: attribute 'a' missing + +({ a ? 1, b }@args: args.a) { b = 1; a = 2; } +# => 2 +``` + ## `if ... then ... else ...` Nix has simple conditional support. Note that `if` is an **expression** in Nix, -- cgit 1.4.1