Using the Rust overlay in a Nix Shell

contents

So, you want a Nix shell to develop your Rust project in, and you also want to use nightly builds of the Rust compiler, either stable or nightly. You also don't want to be restricted to the packaged versions of rustc and cargo in NixOS.

It turns out this is quite simple to pull off with a small derivation, which gives you equivalent semantics to rustup, e.g.:

Also:

This is achieved by cloning the nixpkgs-mozilla overlay locally, and providing it as a path to nix-shell on invocation. Thus, when you pull the local clone, it will update you to the latest toolchain builds, and download them if they are new, and are not already cached in the Nix store, when you enter your nix-shell.

The derivation

This is an example, modify it to suit your needs.

# Use latest nightly Rust
#
# To use, clone the Mozilla overlay, and provide the path at nix-shell
# invocation, e.g.:
#
#     git clone https://github.com/mozilla/nixpkgs-mozilla.git
#     nix-shell nightly.nix -I rustoverlay=/path/to/overlay
#
# If you want to update Rust versions to the nightly builds, just pull the
# overlay repository.

with import <nixpkgs> {};
with import <rustoverlay/rust-overlay.nix> pkgs pkgs;

stdenv.mkDerivation {
  name = "url-bot-rs";

  buildInputs = [
    latest.rustChannels.nightly.rust
    pkgconfig
    openssl
    sqlite
  ];
}

For this to work, you must first clone the overlay repository:

git clone https://github.com/mozilla/nixpkgs-mozilla.git

And point nix-shell to its location:

nix-shell nightly.nix -I rustoverlay=/path/to/overlay

You will now have nice shiny Rust:

[nix-shell:~/git/url-bot-rs]$ rustc --version
rustc 1.45.0-nightly (ed084b0b8 2020-05-15)

Notes

To use stable, just replace:

latest.rustChannels.nightly.rust

with:

latest.rustChannels.stable.rust

This combines various guidance to give you something similar to rustup, and is somewhere between specifying the overlay user-wide, and fetching a given ref for the overlay within your derivation, and I think gives the best of both worlds.

It gives you some control over the toolchain in use, succinctly, and without having to update a ref every time you want to update the toolchain, so gives you a simple derivation you can commit to your project's version control without having to maintain it. You may also want to define a derivation fixing the ref for reproducability, too, perhaps.

References