Nix is a lazily evaluated functional expression language. Attribute sets and lists are common data structures in configurations, but functions, conditionals, recursion, and evaluation are also part of the language itself.
Basic data types#
1. Attribute Sets
This is the most important data structure in Nix.
{
name = "nixos";
version = "24.11"; # 版本号通常用字符串,24.11 是浮点数
isGood = true;
}- Access an attribute:
mySet.name. - Merge attributes: use the
//operator.
2. Lists
Separate items with spaces, not commas!
[ "git" "vim" "htop" ]3. Strings
Double quotes are used for single-line strings; two single quotes delimit multiline strings (Indented Strings).
"single line string"
''
multi
line
string
''- String interpolation: use
${variable}.
Common operators#
//(Merge): merges two attribute sets.{ a = 1; } // { b = 2; }produces{ a = 1; b = 2; }..(Access): accesses nested attributes.pkgs.lib.mkIf.?(Has Property): checks whether an attribute exists.set ? namereturns true/false.
Built-in functions (Builtins)#
Nix provides many built-in functions that are used frequently in configurations:
import ./path.nix: loads another file.builtins.elem x list: checks whether x is in the list.builtins.attrNames set: returns all attribute names.pkgs.lib: although not built in, this is NixOS’s core function library.lib.mkIf condition config: enables configuration conditionally.lib.mkMerge [ ... ]: merges multiple configuration fragments.
Avoiding pitfalls: the semicolon ;#
In Nix, attribute definitions must end with a semicolon.
# 错误
{ a = 1 }
# 正确
{ a = 1; }References & further reading
Adapted from technical notes. Examples use generic names.