精选 Nix 常用指令与核心速查备忘单,涵盖高频用法、配置参数与实用技巧。 本备忘单旨在为编写基础 Nix 声明式配置文件与表达式代码提供快速检索参考。
let
x = "single-line string";
y = ''
multi-line string
'';
in
let
x = -123;
y - 123;
in
let
x = -0.32;
y = 0.45;
in
let
x = true;
y = false;
in
let
x = null;
in
let
x = /absolute/path;
y = ./relative/path;
in
let
x = {
a = 1;
b = 2;
};
y = { c = 3; };
in
let
x = [ 1 2.0 ];
y = [
1
"this is a string"
23.0
null
];
in
↓ 单行注释 (Single-line comment)
# your comment
↓ 多行注释 (Multi-line comment)
/*
your comment
*/
let
x = 1;
y = 2;
in
x + y # -> 返回 3
let
x = 1;
in
{ inherit x; }
↓ 解糖语法等价于 (Desugars to)
let
x = 1;
in
{ x = x; }
let
x = { y = 1; };
in
{ inherit (x) y; }
↓ 解糖语法等价于 (Desugars to)
let
x = { y = 1; };
in
{ y = x.y; }
let
x = { y = 1; z = 2; };
in
with x;
y + z # -> 返回 3
let
x = {
a = 1;
b = 2;
};
y = { c = 3; };
in
{ x = 1; } // { y = 2; } # -> 返回 { x = 1; y = 2; }
{ x = 1; } // { x = 2; } # -> 返回 { x = 2; }
let
x = { y = 1; };
in
x ? y # -> 返回 true
let
x = { y = 1; };
in
x.y # -> 返回 1
↓ 可选默认值 (可选 fallback)
let
x = { y = 1; };
in
x.z or 2 # -> 返回 2
let
f = x: x + 1;
in
f 1 # -> 返回 2
let
f = x: y: [ x y ];
in
f 1 2 # -> 返回 [ 1 2 ]
let
f = {x, y}: x + y;
in
f { x=1; y=2; } # -> 返回 3
↓ 忽略额外参数 (Ignoring arguments)
let
f = {x, y, ... }: x + y;
in
f { x=1; y=2; z=3; } # -> 返回 3
↓ 参数默认值 (默认值s)
let
f = {x, y ? 2 }: x + y;
in
f { x=1; } # -> 返回 3
↓ 绑定整体对象变量 (Bind to variable)
let
f = {x, y}@args: args.x + args.y;
in
f { x=1; y=2; } # -> 返回 3