In this tutorial, you will learn how to initialize a Rust executable project. You can use cargo
for most of the workflow. Thanks to rust-overlay, you can pick a particular channel of the Rust toolchain, and crane builds an executable in a reproducible manner with Nix. Rust Analyzer works out of the box.
Initialize a new project
Make
cargo
executable available:Terminal window nix shell nixpkgs#cargoUse
cargo new
to create a new project:Terminal window cargo new 'your-new-project'Enter the directory:
Terminal window cd 'your-new-project'
Add flake.nix to the project
Initialize the template from the root directory of the project:
Terminal window nix flake init github:akirak/flake-templates#rustBy default, the template will pick the default profile of the latest version from the stable channel. If you prefer a different one, open
flake.nix
and edit the following settings to your preference. Check out the documentation of the Rust Overlay for details:let# For details on these options, See# https://github.com/oxalica/rust-overlay?tab=readme-ov-file#cheat-sheet-common-usage-of-rust-bin## Channel of the Rust toolchain (stable or beta).rustChannel = "stable";# Version (latest or specific date/semantic version)rustVersion = "latest";# Profile (default or minimal)rustProfile = "default";inAdd
.envrc
:Terminal window use flakeAllow direnv:
Terminal window direnv allow
Developing
Use cargo
to develop the project as you would normally do without Nix.
Depending on the project, you may have to add dependencies such as pkg-config
, openssl
, etc. Some of these things are supported in the template, so just check out the flake.nix
and comment out relevant fields.
Building the Nix package
The package is exposed as default
package out of the box, so you can run the application:
nix run .
It is recommended to add the settings for your binary cache to flake.nix
:
nixConfig = { extra-substituters = [ # Use your cachix account "https://akirak.cachix.org" ]; extra-trusted-public-keys = [ # Use a public key for your binary cache "akirak.cachix.org-1:WJrEMdV1dYyALkOdp/kAECVZ6nAODY5URN05ITFHC+M=" ]; };