OFFSET偏移
← All articlesOFFSET / FIELD NOTESNO. 021

Nix syntax: attribute sets, lists, and built-in functions

Learn common data types, attribute access, and the basics of writing configuration expressions.

English translation · Code and commands follow the Chinese original.

IN THESE READING PATHSThe Nix language and build model ↗
About 2 min readStart reading

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 ? name returns true/false.

Built-in functions (Builtins)#

Nix provides many built-in functions that are used frequently in configurations:

  1. import ./path.nix: loads another file.
  2. builtins.elem x list: checks whether x is in the list.
  3. builtins.attrNames set: returns all attribute names.
  4. 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

  1. NixOS Manual ↗
  2. Nix Language Manual ↗

Adapted from technical notes. Examples use generic names.

Continue along a reading path

The Nix language and build model

  1. 01Nix and NixOS: storage, rollback, and declarative thinking
  2. 02Nix syntax: attribute sets, lists, and built-in functions
  3. 03Nix functions and scope
  4. 04Nix attribute sets: recursion and merging
  5. 05Derivations: from expressions to build outputs
CONTINUE READING / NEXT ARTICLENix functions and scope

Identify where each variable comes from in let, inherit, with, and function parameters.