Skip to content

Instantly share code, notes, and snippets.

@shizonic
Forked from abcdw/nix-syntax.org
Created January 2, 2023 06:19
Show Gist options
  • Save shizonic/3f19d8a56c7a4eb69a5a35f3d0514ebf to your computer and use it in GitHub Desktop.
Save shizonic/3f19d8a56c7a4eb69a5a35f3d0514ebf to your computer and use it in GitHub Desktop.

Nix syntax basics

Intro

Comments

# line comments

/* multiline
   comments */

Types

Basic types

[
  true # b
  1 2 3.5
  "hello"
  { k = "v"; k2 = "v2"; } # unorder
  /tmp/file.nix ./file.nix
]

Lazy Reccursive AttrSet

rec { a = "12"; b = "something" + a; c."k1"."${b}" = "value"; }
rec { a = 12; b = { k = b; }; }.b.k

Strings

''
  multi line
   ${toString (10 + 15)}
  string
  with multiple lines''

Conditionals

if is expression

if 3 > 5 then "greater" else "less"

Functions

Simple

a: { t = "test";  b = a; }

Application

((a: a + 1) 2)

More complex

{a ? null, ...}@args: b: { result = args; }

Scope helpers

  • let
  • inherit
  • with
let
  a = { b = { c = "1"; d = 2; }; };
in
with a;
{ inherit (b); }

Imports

import ./test.nix {}

builtins && lib

https://github.com/NixOS/nixpkgs/tree/master/lib
let
  lib = (import <nixpkgs> {}).lib;
in
{ ea = builtins.elemAt; lb = lib.strings; }

loops

There is no loops, oops.

How to live without loops ideas:

  • map
  • filter
  • foldl

Impurities

#{ pkgs ? import <nixpkgs> {} }:
let
  pkgs = import <nixpkgs> {};
  newPkg = pkgs.writeText "hello.txt" "Hello world!";
  # and different fetchSomething functions
in
"${builtins.getEnv "HOME"} and ${newPkg}"

Modules

{ config, pkgs, ...}:
{
  options = {};
  config = {};
}

Home-manager module example.

Links

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment