Nix (language): Difference between revisions
imported>Kcurtet m Typo. The dot is a copy paste error I think. |
imported>Nh2 mention non-shadowing of `with` statement |
||
| Line 294: | Line 294: | ||
==== <code>with</code> statement ==== | ==== <code>with</code> statement ==== | ||
The <code>with</code> statement introduces the lexical scope of | The <code>with</code> statement ([https://nixos.org/manual/nix/stable/#idm140737321918544 link to Nix manual section]) introduces an attrset's value contents into the lexical scope of into the expression which follows. This means that it brings all keys within that set into scope in that expression. So, you don't need to use the dot notation. | ||
Example: | |||
<syntaxHighlight lang=nix> | |||
let | |||
myattrset = { a = 1; b = 2; }; | |||
in | |||
with myattrset; "In this string we have access to ${toString a} and ${toString b}" | |||
</syntaxHighlight> | |||
returns: | |||
<syntaxHighlight lang=nix> | |||
"In this string we have access to 1 and 2" | |||
</syntaxHighlight> | |||
Note that (perhaps surprisingly) <code>with</code> '''does not shadow''' values from outer scope. For example: | |||
<syntaxHighlight lang=nix> | |||
let | |||
a = 333; | |||
in | |||
with { a = 1; b = 2; }; "In this string we have access to ${toString a} and ${toString b}" | |||
</syntaxHighlight> | |||
returns: | |||
<syntaxHighlight lang=nix> | |||
"In this string we have access to 333 and 2" | |||
</syntaxHighlight> | |||
This is because <code>a</code> was already defined in the scope outside the use of <code>with</code>, and <code>with</code> does ''not'' override it. The outer value takes precedence. (It is suspected by the author of this wiki section that the reason for this non-shadowing logic is lexical code stability: In the common usages of <code>with</code> as shown below, the contents of attrsets given to the statement are often large, community-maintained, and frequently updated. If e.g. <code>let myValue = ...; with lib; doSomethingWith myValue</code> shadowed the outer <code>myValue</code> bindings, the people maintaining `lib` could accidentally break this code by adding <code>lib.myValue</code>.) | |||
Common usages are: | Common usages are: | ||
'''On top of expressions''': | '''On top of expressions''': | ||
| Line 310: | Line 344: | ||
} | } | ||
</syntaxHighlight> | </syntaxHighlight> | ||
You will see the with statement a lot at the beginning of expression definition. Most of the time it is used to load the lib functions into the namespace for quick access. | You will see the with statement a lot at the beginning of expression definition. Most of the time it is used to load the lib functions into the namespace for quick access. | ||
<syntaxHighlight lang=nix> | <syntaxHighlight lang=nix> | ||