mirror of
https://codeberg.org/mhwombat/nix-book.git
synced 2026-01-02 19:45:12 +08:00
41 lines
799 B
Text
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"
|
|
....
|
|
====
|