Nix CHEAT SHEET

The Nix quick reference cheat sheet that aims at providing help on writing basic nix code.

7
Sections
24
Cards

#Types & Syntax

String
let
  x = "single-line string";
  y = ''
    multi-line string
  '';
in
Integer
let
  x = -123;
  y - 123;
in
Float
let
  x = -0.32;
  y = 0.45;
in
Boolean
let
  x = true;
  y = false;
in
Null
let
  x = null;
in
Path
let
  x = /absolute/path;
  y = ./relative/path;
in
Attribute Set
let
  x = {
    a = 1;
    b = 2;
  };
  y = { c = 3; };
in

see Attribute Sets

List
let
  x = [ 1 2.0 ];
  y = [
    1
    "this is a string"
    23.0
    null
  ];
in
Comment

↓ single-line comment

# your comment

↓ multi-line comment

/*
  your comment
*/

#Scoping

Define Local Variable
let
  x = 1;
  y = 2;
in
  x + y # -> returns 3
Add Variables Into Scope
let
  x = 1;
in
  { inherit x; }

↓ desugars to

let
  x = 1;
in
  { x = x; }
Add Attributes Into Scope
let
  x = { y = 1; };
in
  { inherit (x) y; }

↓ desugars to

let
  x = { y = 1; };
in
  { y = x.y; }
Add All Attributes Into Scope
let
  x = { y = 1; z = 2;  };
in
  with x;
  y + z # -> returns 3

#Conditionals

Define Conditionals
if x > 0
then 1
else -1

#Attribute Sets

Define Attribute Sets
let
  x = {
    a = 1;
    b = 2;
  };
  y = { c = 3; };
in
Update Attribute Sets
{ x = 1; } // { y = 2; } # -> returns { x = 1; y = 2; }
{ x = 1; } // { x = 2; } # -> returns { x = 2; }
Check For Attribute
let
  x = { y = 1; };
in
  x ? y # -> returns true
Reference Attirbute Keys
let
  x = { y = 1; };
in
  x.y # -> returns 1

↓ optional

let
  x = { y = 1; };
in
  x.z or 2 # -> returns 2

#Concatenation & Interpolation

Concatenate Lists
[ 1 2 ] ++ [ 3 4 ] # -> returns [ 1 2 3 4 ]
Concatenate Paths & Strings
/bin + /sh # -> returns /bin/sh
/bin + "/sh" # -> returns /bin/sh
"/bin" + "/sh" # -> returns "/bin/sh"
Interpolate Strings
let
  x = "bar";
in
  "foo ${x} baz" # -> returns "foo bar baz"

#Functions

Simple Function
let
  f = x: x + 1;
in
  f 1 # -> returns 2
Multiple Arguments
let
  f = x: y: [ x  y ];
in
  f 1 2 # -> returns [ 1 2 ]
Named Arguments
let
  f = {x, y}: x + y;
in
  f { x=1; y=2; } # -> returns 3

↓ ignoring arguments

let
  f = {x, y, ... }: x + y;
in
  f { x=1; y=2; z=3; } # -> returns 3

↓ default values

let
  f = {x, y ? 2 }: x + y;
in
  f { x=1; } # -> returns 3

↓ bind to variable

let
  f = {x, y}@args: args.x + args.y;
in
  f { x=1; y=2; } # -> returns 3

#Sources