Nix Language Quirks: Difference between revisions

Merge the conditional key names entry just I added with the existing using null as a key name, and just add the more clear example of using conditionals
Change the title of the ${null} attribute set entry since delete is misleading. Also link to the official documentation about it
Line 193: Line 193:
</syntaxHighlight>
</syntaxHighlight>


== Using null as key in attribute set deletes the attribute ==
== Attribute set entries with a name that evaluates to null will not be added to the set ==


<syntaxHighlight lang=nix>
From [https://nix.dev/manual/nix/2.24/language/syntax#attrs-literal this] section of the Nix Reference Manual:
nix-repl> { ${null} = "value"; key = "value2"; }
 
{ key = "value2"; }
<blockquote>
</syntaxHighlight>
In the special case where an attribute name inside of a set declaration evaluates to null (which is normally an error, as null cannot be coerced to a string), that attribute is simply not added to the set:
 
{ ${if foo then "bar" else null} = true; }
 
This will evaluate to {} if foo evaluates to false.
</blockquote>
 
The relevant source can be found [https://github.com/NixOS/nix/blob/26c3fc11eada3fa7df0284190095868a947fefe2/src/libexpr/eval.cc#L1249-L1250 here].


This can be (ab)used to conditionally include or exclude attribute set entries, for example:
This feature can be used to conditionally include or exclude attribute set entries, for example:


<syntaxHighlight lang=nix>
<syntaxHighlight lang=nix>
Line 210: Line 217:
</syntaxHighlight>
</syntaxHighlight>


This might used as an alternative to conditionally merging attribute sets using <code>//</code> like the following:
<syntaxHighlight lang=nix>
{ a = "b"; } // (if true then { foo = "bar"; } else { } )
</syntaxHighlight>


== Nix Language FAQ ==
== Nix Language FAQ ==