Control Flow
Nix is a functional language to behave as no side-effect, all variables are isolated in scope and all controls flow statement can have implicit return.
Let-in
let..in statement is used to create a isolated scope to perform operation on variable declared after let and requires a return after in.
nix
let
foo = 1;
in
foo # foo is returned1
2
3
4
2
3
4
Since it supports implicit return, you store the value to a variable.
nix
let
foo =
let
bar = 123;
in
bar + 1;
in
foo1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
NOTE
Child scope inside let..in statement can access variables from parent scope.
Value Fallback
nix
foo or "foo"
# equvalent to
if foo != null then foo else "foo"1
2
3
2
3
With Local Expanding
with works similarly to let..in, it creates a new scope and implicitly declares all attributes of a set as variables into the new scope.
nix
let
foo = {
bar = 123;
baz = 123;
};
in
with foo;
{
inherit bar; # foo.bar and foo.baz is available in scope as variables #
inherit baz;
}1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
If a attribute expanded by with conflicts with any variable in scope by its name, the variable is preferred.
nix
let
foo = {
bar = 123;
};
bar = 456;
in
with foo;
{
inherit bar; # bar = 456 #
}1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10