Master Nix inherit Keyword in 5 Minutes

by|inArticles||2 min read
Learn Nix<br>
Learn Nix<br>

In Nix, a purely functional package management system, the inherit keyword is used to simplify expressions by avoiding repetition. It allows you to import variables from an outer scope into an attribute set. Here's a detailed explanation along with examples:

Basic Explanation

Without inherit: Normally, when you want to include variables from the outer scope into an attribute set, you would have to repeat the variable name. For example:

let packageName = "example"; version = "1.0"; in { name = packageName; version = version; }

With inherit: The inherit keyword allows you to include these variables without repeating their names.

let packageName = "example"; version = "1.0"; in { inherit packageName version; }

Here, inherit packageName version; automatically creates attributes packageName and version in the attribute set, assigning them the values from the outer scope.

Advanced Usage

Inheriting from another set: You can also use inherit to import attributes from another set. For example:

let src = { packageName = "example"; version = "1.0"; }; in { inherit (src) packageName version; }

This will create an attribute set with packageName and version taken from the src set.

Inheriting in function arguments: It's common in Nix to use inherit in function arguments to reduce boilerplate. For instance:

{ stdenv, fetchurl, inherit (gnome3) glib; }: stdenv.mkDerivation { name = "my-package"; buildInputs = [ glib ]; src = fetchurl { url = "http://example.com/my-package.tar.gz"; sha256 = "0abc123..."; }; }

Here, inherit (gnome3) glib; means that glib is taken from the gnome3 package set and used as a part of the function's arguments.

Conclusion

The inherit keyword in Nix is a powerful tool to avoid repetition and make code more concise. It's particularly useful in large Nix expressions where several variables or attributes from an outer scope or another set are required in the current scope.

Thank you for reading this far! Let’s connect. You can @ me on X (@debilofant) with comments, or feel free to follow. Please like/share this article so that it reaches others as well.

Related Articles

© Copyright 2024 - ersocon.net - All rights reservedVer. 415