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

52 lines
914 B
Text

= Let expressions
A `let` expression defines a value with a local scope.
[source]
.Example
....
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]
.Example
....
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]
.Example
....
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]
.Example
....
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