gpt4 book ai didi

nix nixlang : undefined variable pkgs in default. nix via nix-build -A hello 但在 nix repl 中工作

转载 作者:行者123 更新时间:2023-12-04 10:36:56 26 4
gpt4 key购买 nike

我写了一个非常简单的 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 via nix-build -A hello 但在 nix repl 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60131414/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com