nix-book/source/nix-language/let.adoc
2023-12-02 15:29:29 +00:00

48 lines
878 B
Text

= Let expressions
A `let` expression defines a value with a local scope.
[source]
....
nix-repl> let x = 3; in x*x
9
nix-repl> let x = 3; y = 2; in x*x + y
11
....
You can also nest `let` expressions.
The previous expression is equivalent to the following.
[source]
....
nix-repl> let x = 3; in let y = 2; in x*x + y
11
....
[IMPORTANT]
====
A variable defined inside a `let` expression will "shadow" an outer variable with the same name.
[source]
....
nix-repl> x = 100
nix-repl> let x = 3; in x*x
9
nix-repl> let x = 3; in let x = 7; in x+1
8
....
====
A variable in a let expression can refer to another variable in the expression.
This is similar to how recursive attribute sets work.
[source]
....
nix-repl> let x = 3; y = x + 1; in x*y
12
....
// TODO Discuss inheriting attributes https://nixos.org/manual/nix/stable/language/constructs#inheriting-attributes