我编写了一个非常简单的 default.nix 文件,用它我应该能够构建 gnu hello 包(类似于 nix-pills)。
但是现在我遇到了一个错误:
[jane@nixos:~/graphviz]$ nix-build -A hello
error: undefined variable 'pkgs' at /home/jane/graphviz/default.nix:3:47
这是源代码:
[jane@nixos:~/graphviz]$ cat default.nix
{
pkgs = import <nixpkgs> {};
mkDerivation = import ./autotools.nix pkgs;
hello = import ./hello.nix { inherit mkDerivation ;};
}
这对我来说完全没有意义,因为我定义了 pkgs 上面的行。
由于我看不出出了什么问题,所以我打开了 nix repl 并输入了这些行。
nix-repl> pkgs = import <nixpkgs> {}
nix-repl> mkDerivation = import ./autotools.nix pkgs
nix-repl> hello = import ./hello.nix { inherit mkDerivation ;}
nix-repl> hello
«derivation /nix/store/g2y6sf5q236icvv2gwyg0lnij3mkr36j-hellooo.drv»
瞧,它起作用了。所以我不明白为什么 default.nix 会失败。我只能想象 default.nix 有点特殊,但语法方面它一定没问题,否则 nix repl 将无法正常工作。
任何人都可以解释为什么我会收到此 undefined variable 错误吗?
编辑:在提出问题后,我找到了一种解决 undefined variable 错误的方法,如果我这样说:
let pkgs = import <nixpkgs> {}; mkDerivation = import ./autotools.nix pkgs;
in
{
hello = import ./hello.nix { inherit mkDerivation ;};
}
它有效。
但我原来的问题仍然存在。
最佳答案
{ }
语法仅定义一个值。它不会将其中的属性纳入范围。您可以使用 rec { }
语法来同时执行这两项操作。
rec {
pkgs = import <nixpkgs> {};
mkDerivation = import ./autotools.nix pkgs;
hello = import ./hello.nix { inherit mkDerivation ;};
}
nix repl 的作用本质上是在每次命名时创建一个 let
绑定(bind)。您的 repl session 可以被认为是交互式构建的表达式:
let pkgs = import <nixpkgs> {};
in /* nixlang scope on 2nd prompt */
let mkDerivation = import ./autotools.nix pkgs
in /* nixlang scope on 3rd prompt */
let hello = import ./hello.nix { inherit mkDerivation ;}
/* nixlang scope on 4th prompt */
in hello
为了说明属性集创建和名称绑定(bind)之间的区别,您可以命名属性集并在其自己的定义中使用它
let
myScope = {
# myScope is like any other attribute set
pkgs = import <nixpkgs> {};
# laziness permits the attributes inside to reference myScope
mkDerivation = import ./autotools.nix myScope.pkgs;
hello = import ./hello.nix { inherit (myScope) mkDerivation ;};
};
in
# the value of this file is the myScope attribute set
myScope
这相当于 rec
示例,但仅将单个名称引入范围:myScope
。
关于nix nixlang : undefined variable pkgs in default. nix 通过 nix-build -A hello 但可以在 nix repl 中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60131414/