Skip to content

Conversation

hailangx
Copy link

This PR implements automatic merging of related use statements from the same crate or module, addressing the feature request to improve code readability and reduce import duplication.

Problem

Currently, rustfmt does not automatically merge multiple use statements from the same crate or module. For example:

use std::collections::HashMap;
use std::collections::BTreeMap;
use std::collections::HashSet;

Would remain unchanged instead of being merged into a cleaner, more idiomatic format.

Solution

Changed the default ImportGranularity setting from Preserve to Crate, enabling automatic import merging by default. This leverages existing, well-tested functionality that was previously opt-in.

Results

With this change, the above imports are now automatically formatted as:

use std::collections::{BTreeMap, HashMap, HashSet};

More complex examples also work correctly:

// Before
use std::fs::File;
use std::io::Read;
use std::path::Path;
use std::collections::HashMap;
use serde::Serialize;
use serde::Deserialize;

// After
use std::{
    collections::HashMap,
    fs::File,
    io::Read,
    path::Path,
};

use serde::{Deserialize, Serialize};

Compatibility

  • Existing configurations preserved: Files with explicit imports_granularity settings continue to work exactly as before
  • All tests pass: Core import functionality remains unchanged
  • Gradual adoption: Users can opt out by setting imports_granularity = "Preserve" in their configuration

Benefits

  • Improved readability: Eliminates repetitive import statements
  • Cleaner codebase: Follows Rust community conventions for organized imports
  • Zero configuration: Works automatically without requiring users to discover and configure the option
  • Consistent formatting: Uses rustfmt's existing multi-line import formatting rules

This change makes rustfmt more helpful out of the box while maintaining full backward compatibility for users with specific formatting preferences.


✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.

@ytmimi
Copy link
Contributor

ytmimi commented Sep 16, 2025

See #6658 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants