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