When transitioning to Rust 2018 edition, it becomes necessary to use :: in use statements (e.g. use ::actix::prelude::*) in order to compile one's code. Unfortunately rustfmt removes these when formatting the code.
Although cargo fmt does work in these cases, many tools actually use rustfmt since it's easier to integrate into editors (e.g. rust-mode in Emacs). This makes it impossible to write 2018 code in those editors without tweaking.
You need to add a rustfmt.toml with edition = 2018 in it. Cargo fmt picks this up from Cargo.toml, but Rustfmt can't do that. Editor plugins can also pass this info (the RLS does this).
Closing this issue probably needs some docs adding to README.md
@nrc yes, adding a noticeable explanation about this in the README is a good idea IMO. Thanks for the help!
This doesn't seem to be working regardless of the edition specified, at least on stable (rustfmt 1.0.0-stable (4a4e508 2018-11-29)). Am I missing something? To reproduce:
cargo new rustfmt-3241
cd rustfmt-3241
echo 'edition = "2018"' > rustfmt.toml
# Using libc instead of the actual ignore crate to speed up compilation
echo 'ignore = { package = "libc", version = "0.2.45" }' >> Cargo.toml
sed -i '1iuse ::ignore;' src/main.rs
cat src/main.rs
# use ::ignore;
# fn main() {
# println!("Hello, world!");
# }
cargo check
So far, so good. Now, let's use rustfmt, with --edition 2018 to be triple-sure that the correct edition is used:
rustfmt --edition 2018 src/main.rs
cat src/main.rs
# use ignore;
# fn main() {
# println!("Hello, world!");
# }
cargo check
# error[E0658]: imports can only refer to extern crate names passed with `--extern` on stable channel (see issue #53130)
rustfmt did remove the :: from the use statement, breaking the program.
Combined with #3273 and an editor that auto-formats on save, this is somewhat frustrating.
@Deewiant is the edition set to 2018 in your Cargo.toml too?
@nrc Yes, as per the default from cargo new these days.
This is quite annoying. It will leave something like use ::foo::{self, bar}; alone but just plain use ::foo; will have the :: stripped even with 2018 enabled everywhere etc.
i'll try to fix this if nobody's on that.
Most helpful comment
You need to add a rustfmt.toml with
edition = 2018in it. Cargo fmt picks this up from Cargo.toml, but Rustfmt can't do that. Editor plugins can also pass this info (the RLS does this).Closing this issue probably needs some docs adding to README.md