Search code examples
nix

Nix: nixlang syntax how to change an existing set ? Syntax error unexpected '=' , expecting $end


nix repl
nix-repl> test = {"a"=10;}
nix-repl> test.a
nix-repl> 10
nix-repl> test.a=20
error: syntax error, unexpected '=' , expecting $end, at (string):1:7

Expected result:

test = {"a"=20;}

I am currently learning nix and couldn't find the answer after a few minutes of google. This seems rather simple and I'm sure someone instantly knows this.


Solution

  • Values in nix are immutable; you can't change the value of test.a, because that would require changing the set. You can only create a new set with a different a value.

    nix-repl> test = {"a"=10;}
    
    nix-repl> test // {"a"=20;}
    { a = 20; }
    
    nix-repl> test
    { a = 10; }
    
    nix-repl> test2 = test // {"a"=20;}
    
    nix-repl> test2
    { a = 20; }
    

    The // operator combines two sets, with values on the right-hand side overriding values on the left.

    nix-repl> {"a"=10; "b"=20;} // {"a"="changed"; c="30";}
    { a = "changed"; b = 20; c = "30"; }