i also had problems with this when first starting out with nix development environments. some points from my experience:
run cargo clean always after switching toolchain version/distribution so the target dir is emptied which may contain build artifacts from a different rust version which are incompatible with your current toolchain. this is also necessary when using rustup, not nix-specific.
make sure that all parts of your toolchain are from one version. builds will break if e.g. you have cargo 1.72 from the nix shell but rustc 1.74 from the global environment. same goes for clippy, rustfmt, rust-analyzer (wrapped to use a specific rust-src version in nixpkgs), etc.
the entire toolchain is installed using fenix, so there should be no mismatches
I have cargo cleaned a lot, and have also manually deleted the target directory
This only happens when I have my crate split into a library and multiple binaries. Moreover, cargo build doesn’t actually fail, although cargo check --all-targets does. Even more confusingly, cargo check only fails when given both --lib and --bins at the same time (running them one at a time works). I also get these errors inside rust analyzer, which makes the language server pretty much unusable. Any ideas about what the cause of this might be?
I am installing the whole toolchain at once — no instances of withComponents
I am using no cargo plugins
I tried looking at my path, but it seems to all be nix store stuff. Rust tooling was not available outside the shell, so I assume the tooling I was getting inside the shell was the correct one.
The “fix” for me was setting "rust-analyzer.cargo.allTargets": false in my neovim config, which made rust analyzer not pass the --all-targets flag to cargo (that flag seems to be the root of all evil in this case).
I should mention that I ended up making my project work on stable rust too, and using the stable pkgs.rustc and pkgs.cargo from nixpkgs did not solve this issue (i.e., the error was the same, no matter how many times I deleted my target directory).