nix-book/source/nix-language/with.adoc
Amy de Buitléir 96f65dd5a5 expanded
2025-10-12 15:59:19 +01:00

41 lines
799 B
Text

= With expressions
A `with` expression is somewhat similar to a `let` expression,
but it brings all of the associations in an attribute set into scope.
[source]
.Example
....
nix-repl> point = { x1 = 3; x2 = 2; }
nix-repl> with point; x1*x1 + x2
11
....
[IMPORTANT]
====
Unlike a `let` expression, a variable defined inside a `with` expression will _not_
"shadow" an outer variable with the same name.
[source]
.Example
....
nix-repl> name = "Amy"
nix-repl> animal = { name = "Professor Paws"; age = 10; species = "cat"; }
nix-repl> with animal; "Hello, " + name
"Hello, Amy"
....
However, you can refer to the variable in the inner scope
using the attribute selection operator (`.`).
[source]
.Example
....
nix-repl> with animal; "Hello, " + animal.name
"Hello, Professor Paws"
....
====