({ a }: a) { a = 4; b = 5; } error: anony-6ren">
gpt4 book ai didi

nix - Nix 的 "callPackage"如何调用没有省略号定义的函数?

转载 作者:行者123 更新时间:2023-12-04 12:17:01 24 4
gpt4 key购买 nike

要调用使用集合解构的 Nix 函数,您需要向它传递一个集合,其中包含它所需的确切键,不多也不少:

nix-repl> ({ a }: a) { a = 4; b = 5; }
error: anonymous function at (string):1:2 called with unexpected argument ‘b’, at (string):1:1

异常(exception)情况是,如果函数的参数列表末尾包含省略号:
nix-repl> ({ a, ... }: a) { a = 4; b = 5; }
4

但是, nixpkgs 中的大多数软件包由 default.nix 组成包含未使用此省略号定义的函数的文件。然而,不知何故,当您使用 callPackage 时,它设法调用这些函数并只传递它们需要的参数。这是如何实现的?

最佳答案

有一个反射 primop,可以解构函数参数:

nix-repl> __functionArgs ( { x ? 1, y }: x )
{ x = true; y = false; }
callPackage 然后迭代这些属性名称,获取所需的包并构造包的属性集,稍后将其提供给被调用的函数。
这是一个简单的例子:
nix-repl> callWithExtraArgs = f: args:
let
args' = __intersectAttrs (__functionArgs f) args;
in
f args'

nix-repl> callWithExtraArgs ({ x }: x + 1) { x = 4; y = 7; }
5

要浏览 Nix primops,请转至 15.5. Built-in FunctionsNix manual (或见 the docs of the unstable branch)。

关于nix - Nix 的 "callPackage"如何调用没有省略号定义的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46083266/

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