How to Eliminate "use xxx::prelude::*"
Contents
When pulling certain third-party crates into a Rust project, such as stream processing frameworks, data computation pipelines, or configuration rule engines, many developers run into a baffling compiler error in their application code.
Suppose you have a Var<String> variable msg representing text, or a Var<i64> variable count representing a counter. You follow the documentation examples and write a basic prefix check or arithmetic operation:
let rule = msg.starts_with("ERR:");And the compiler immediately rejects it:
error[E0599]: no method named `starts_with` found for struct `Var<String>` in the current scope
--> src/main.rs:12:20
|
12 | let rule = msg.starts_with("ERR:");
| ^^^^^^^^^^^ method not found in `Var<String>`
|
= help: items from traits can only be used if the trait is in scopeWhy does Var<String>, which clearly holds a string type, fail to call .starts_with()?
A look at the source code of these libraries reveals the reason: the methods that naturally belong to the type have been split up by feature category into fine-grained extension traits:
pub trait CompareExt {
fn eq(self, rhs: Self) -> Rule;
}
pub trait NumericExt {
fn add(self, rhs: Self) -> Self;
}
pub trait TextExt {
fn starts_with(self, prefix: &str) -> Rule;
}From the perspective of internal code organization, splitting capabilities into separate traits and implementing them for the relevant types looks clean and single-purpose, fitting traditional software engineering dogma. The trouble starts when a caller brings the library into an application module.
Callers Forced to Memorize Manuals, and the prelude::* Band-Aid
In most object-oriented languages, once a type implements an interface, its methods travel with the instance wherever it goes. In Rust, the rule is completely different: even when a struct implements a trait, you cannot call any method on that trait unless the trait is explicitly brought into the current lexical scope with use.
As a result, when an application developer gets hold of a struct instance and presses ., the core methods they expect do not show up in autocomplete at all. To call a method normally, only two options remain: rely on the IDE to scan the dependency tree, guess which trait hides the method, and auto-insert the use statement; or dig through the manual and memorize which trait owns which method. Without IDE assistance, or when the IDE fails to guess, developers often have no idea which import line is missing.
In a moderately complex library, a single core type often has seven, eight, or even over a dozen fine-grained extension traits hanging off it: CompareExt, TextExt, NumericExt, FormatExt, BatchExt, and so on. Asking users to manually import a row of traits before writing business logic quickly makes the library painful to use.
To paper over this friction, the community settled on an unspoken convention: bundle all those fragmented traits into a prelude module and tell users to paste a fixed line at the top of every source file:
use xxx::prelude::*;That line saves the trouble of importing traits one by one, yet it fails to solve the underlying problem and trades it for a new set of engineering hazards:
- Namespace pollution and method name collisions. Dumping a dozen traits into the current scope with a wildcard
*easily triggers method name clashes. As soon as an application module pulls inprelude::*from two or three crates at once, common method names like.filter(),.get(),.map(), and.parse()collide, forcing the caller to fall back on verbose fully qualified syntax like<MyType as some_crate::Trait>::method(&x). - Blind spots in code reading and review. When reading code on the web or during code review without IDE hover tooltips, you might see three different
prelude::*imports at the top of a file anditem.process()below, with no way to tell which crateprocesscomes from or which trait it belongs to. - Fragmented documentation lookup. When you open
docs.rsto check how a core struct works, its primaryMethodssection is often completely empty. Every useful API has been scattered and collapsed into a dense wall ofTrait Implementationsat the very bottom of the page, making lookup unnecessarily slow.
A design originally intended for decoupling and categorization ends up making life miserable for callers because it packs a type's own core methods into traits and pushes the import burden onto users, resulting in a leaky abstraction.
What Are Traits Actually For?
To untangle this knot, we need to look at Rust's underlying mechanics: Rust requires use Trait before calling a trait method in order to prevent global method name collisions.
In Rust, traits are open to the world. As long as the orphan rule is satisfied, any downstream crate can implement a new trait and attach new methods to an existing type. If every trait method were callable directly without an explicit use, then the moment two third-party crates happened to extend String with a .to_slug() method, your entire project would hit a naming collision and fail to compile.
For that reason, Rust strictly confines the visibility of trait methods to the current lexical scope. Only extensions explicitly brought in via use take effect.
Exposing methods through trait imports was designed as an isolation mechanism for cross-crate external extensions; a type's native core methods were never meant to be exposed through that mechanism.
When you design a library, two distinct responsibilities exist within the type system:
- Surface behavior for the caller. What a user can do when they hold an instance of a type and press
.belongs to the type's native capabilities. These methods should be defined directly inside the type's ownimpl Typeblock as inherent methods. Inherent methods are permanently welded to the type: wherever an instance goes, its methods go with it, requiring zerouseimports and always appearing front and center on the first screen ofdocs.rs. - Backstage contracts for the compiler. Which types are permitted to call which methods? What conditions must arguments passed to internal polymorphic functions satisfy? This is the true role of a trait: acting as a compile-time type contract, sitting quietly inside a function signature's
whereclause to check tickets at the gate.
Many designs in the ecosystem that force users to write use xxx::prelude::* get these two responsibilities backward. To categorize types and reuse code internally, they turn their internal permission ledgers (NumericExt, TextExt, FormatExt) directly into public traits carrying methods, leaving the struct itself an empty shell devoid of inherent methods. That forces application developers to memorize the library's internal categorization ledger and manually import it into scope just to call methods that belonged to the type in the first place.
To return an API to an intuitive "what you see is what you get" experience and eliminate prelude::* for good, there is only one path: weld every public method back onto the struct as a pure inherent method, and strip public methods off the traits so they retreat behind the where bounds of those inherent methods as invisible compile-time gatekeepers.
Welding Methods to the Surface, Moving Contracts Behind where
The problem now becomes how to precisely control which instances can call which inherent methods based on their type, without putting methods into traits and without copy-pasting code.
Let's break this down step by step, starting with the generic variable Var<T> from earlier.
Our goal is for Var<T> to satisfy the following behavior:
- Every
Var<T>can call.eq(rhs)for equality comparison; - Only when
Tis a numeric type (such asi64orf64) canVar<T>call.add(rhs); - Only when
Tis a text type (such asString) canVar<T>call.starts_with(prefix).
If we write pub trait NumericExt { fn add... }, the user has to import a trait. If we write separate inherent methods on impl Var<i64> and impl Var<f64>, we have to duplicate the code for every numeric type.
Rust's impl<T> Var<T> block already provides a built-in solution, because where bounds can be placed not only on an entire impl block, but also on individual inherent methods.
First, we define two empty contract markers, Numeric and Textual, containing no methods at all:
// Pure compile-time classification contracts with no public methods
pub trait Numeric {}
impl Numeric for i64 {}
impl Numeric for f64 {}
pub trait Textual {}
impl Textual for String {}
impl Textual for &'static str {}Next, we write all methods directly on Var<T> as inherent methods, letting the empty contracts retreat into each method's where clause to guard the door:
pub struct Var<T> {
name: &'static str,
_marker: PhantomData<T>,
}
impl<T> Var<T> {
// No extra bounds: callable on any Var<T>
pub fn eq(self, rhs: T) -> Rule { /* ... */ }
// This inherent method is available only when T satisfies the Numeric contract
pub fn add(self, rhs: T) -> Calc<T>
where
T: Numeric {
/* ... */
}
// This inherent method is available only when T satisfies the Textual contract
pub fn starts_with(self, prefix: &str) -> Rule
where
T: Textual {
/* ... */
}
}Now .eq(), .add(), and .starts_with() are all inherent methods on Var<T>. Callers don't need a single use import in their application files: when they take a count (Var<i64>) variable and press ., the IDE immediately pops up .eq() and .add(). At the same time, because the compiler checks in the background and sees that i64 does not satisfy the Textual contract, .starts_with() never appears in the autocomplete list.
When One Struct Becomes Many
Now let's raise the system complexity by an order of magnitude and see whether this design still holds up when a library has multiple expression structs playing different roles.
In a more complete computation pipeline or expression engine, beyond Var<T> for initial variables, you will also have Calc<T> for arithmetic results, Trim<E> for stripping leading and trailing whitespace, Len<E> for computing byte length, and Total<E> for aggregating values across multiple records. Every transformation or function call produces a node struct with a distinct role:
pub struct Var<T> { /* ... */ }
pub struct Calc<T> { /* ... */ }
pub struct Trim<E>(pub E);
pub struct Len<E>(pub E);
pub struct Total<E>(pub E);We want all nodes to chain together naturally: whether an expression is an initial variable count, an arithmetic result count.add(10), a function call len(msg), or an aggregation total(count), as long as it represents a value, it should be able to keep calling .eq(), .add(), or .starts_with().
This brings up another obstacle: in Rust, inherent methods cannot be inherited across structs. If we wrote inherent methods directly on each node struct, dozens of methods like .eq(), .add(), and .starts_with() would have to be implemented repeatedly across Var, Calc, Trim, Len, Total, and so on. With ten node types, you would have to copy and paste them ten times.
This is the exact turning point where most DSLs and stream processing libraries break down and fall back to pub trait ExprExt + use xxx::prelude::*. With a trait, a single blanket implementation impl<E: ExprNode> ExprExt for E attaches the methods to every struct at once, which is simple and intuitive to write, whereas inherent methods cannot do the same.
We don't actually need to copy and paste code across structs. Since inherent methods can only live on a single struct, and we have many different internal nodes that need to share those methods, the way through is straightforward: wrap every internal node inside a single lightweight outer shell, Expr<T>.
pub struct Expr<T>(pub T);Architecturally, this zero-cost Expr<T> wrapper acts as an inherent method hub. Whether the internals branch out into twenty or fifty distinct operation nodes, the library only ever exposes Expr<T> as its public expression type. Every .eq(), .add(), and .starts_with() inherent method only needs to be written once on impl<T> Expr<T>.
Compile-Time Capability Transitions and Two-Dimensional Gating
In the earlier Var<T>, the generic parameter T was a concrete value type like i64 or String, so writing where T: Numeric or where T: Textual directly was enough. Inside Expr<T>, however, the wrapped T is a nested expression struct of arbitrary depth. On top of that, as functions nest around an expression, its output type transforms dynamically.
Consider a concrete example. Suppose we have a text variable msg representing a log message, with the type Expr<Var<String>>:
- Initially, its output type is
String, so it can call the text method.starts_with("ERR:"), while the arithmetic method.add(10)is unavailable; - When we wrap it in a whitespace-stripping function
trim(msg), the resulting type isExpr<Trim<Var<String>>>, whose output type is stillString; - When we wrap it further in a length function
len(trim(msg)), the resulting type becomesExpr<Len<Trim<Var<String>>>>. The momentlen(...)wraps the expression, its semantic output changes fromStringto the integer typei64.
At that point, when the user types len(trim(msg))., the text-only .starts_with() method must immediately disappear from the type, while the previously forbidden arithmetic method .add(10) must unlock at that exact moment, letting the user write a single fluid chain:
let rule = len(trim(msg)).add(10).eq(25);To achieve this compile-time capability transition, we introduce a simple internal evaluation contract Eval, allowing each internal node to report its final output type through an associated type Out:
pub trait Eval {
type Out;
}
// 1. The output type of an initial variable Var<T> is T itself
impl<T> Eval for Var<T> {
type Out = T;
}
// 2. The arithmetic node Calc<T> erases its left and right child nodes, keeping only the resulting numeric type T
impl<T> Eval for Calc<T> {
type Out = T;
}
// 3. Trim<E> requires its inner node E to produce text, and continues to output String
impl<E: Eval> Eval for Trim<E>
where
E::Out: Textual {
type Out = String;
}
// 4. Capability transition point: Len<E> accepts an inner node E that produces text, and shifts its own Out to i64
impl<E: Eval> Eval for Len<E>
where
E::Out: Textual {
type Out = i64;
}Linked through Eval::Out, the data-domain inherent methods on the outer hub Expr<T> never need to care how many struct layers are nested inside; they only need to check the computed T::Out:
impl<T: Eval> Expr<T> {
// Any valid expression can be compared for equality with a value of the same output type
pub fn eq(self, rhs: T::Out) -> Rule { /* ... */ }
// Whenever the current node's computed Out satisfies Numeric, the inherent method .add() is unlocked
pub fn add(self, rhs: T::Out) -> Expr<Calc<T::Out>>
where
T::Out: Numeric {
/* ... */
}
// Whenever the current node's computed Out satisfies Textual, the inherent method .starts_with() is unlocked
pub fn starts_with(self, prefix: &str) -> Rule
where
T::Out: Textual {
/* ... */
}
}We then pair this with two short function constructors:
pub const fn trim<E: Eval>(expr: Expr<E>) -> Expr<Trim<E>>
where
E::Out: Textual {
Expr(Trim(expr.0))
}
pub const fn len<E: Eval>(expr: Expr<E>) -> Expr<Len<E>>
where
E::Out: Textual {
Expr(Len(expr.0))
}If we look back at len(trim(msg)).add(10).eq(25), the compiler's inference chain behind the scenes becomes clear:
msghasOut = String, which satisfiesTextual;- After
trim(msg),OutremainsString; - Upon passing through
len(...),Len'sEvalimplementation shiftsOuttoi64. Becausei64does not satisfyTextual, the outerExprautomatically strips away.starts_with()and all other text methods; at the same time, becausei64satisfiesNumeric, it automatically exposes arithmetic methods like.add(); - Next, when
.add(10)is called, following the boundary erasure principle established in the previous post, the nestedLen<Trim<...>>is converted on the spot into an internal AST node, collapsing the return type into a flatExpr<Calc<i64>>.
Even though .add() and .starts_with() only inspect T::Out, we still need to keep the internal structural type T inside Expr<T>, rather than erasing every node into Expr<i64> or Expr<String> from the very beginning.
In a complete expression system, what a node is allowed to do depends on two orthogonal dimensions:
- Data-domain capabilities (checking the output type
T::Out). Whether the computed result is numeric, textual, or boolean directly determines whether the node can perform arithmetic operations or prefix matching. - Structural-role capabilities (checking the node structure
Titself). Whether the node acts as a writable source variable, a pure function transformation, or a multi-row aggregation node in the computation graph determines which structural operation permissions it holds.
Take a simple example: a source variable count (Expr<Var<i64>>), a length expression len(msg) (Expr<Len<...>>), and a batch aggregation total(count) (Expr<Total<...>>) all share the output type T::Out = i64, so all three can call .add(10) and .eq(100).
In terms of structural roles, however, their permissions differ completely:
- Only a source variable
Var<T>is allowed to call.set(val)to mutate an initial value, because writinglen(msg).set(10)on a computed length ortotal(count).set(100)on an aggregated total makes no sense; - Conversely, only an aggregation node
Total<E>is allowed to call.dedup()to deduplicate records before summing, whereas writingcount.dedup()on a single scalar variable is meaningless.
By preserving the two-layer structure of Expr<T>, we can enforce both gates on the same inherent method hub: data operation methods check T::Out, while node role methods check T itself:
// Empty structural-role contracts controlling write permissions and aggregation modifiers
pub trait Writable {}
pub trait Reducible {}
// 1. Only source variables are allowed to be assigned new values
impl<T> Writable for Var<T> {}
// 2. Only aggregation nodes are allowed to call the deduplication modifier
impl<E> Reducible for Total<E> {}
impl<T: Eval> Expr<T> {
// Guarded on T itself: only source variables have the .set() inherent method
pub fn set(self, val: T::Out) -> Mutation
where
T: Writable {
/* ... */
}
// Guarded on T itself: only aggregation nodes have the .dedup() inherent method
pub fn dedup(self) -> Self
where
T: Reducible {
/* ... */
}
}Scaling Up to a Full SQL Syntax Tree
The example above was a warm-up. Now let's place this architecture into a domain language like SQL, with dozens of data types and rich syntactic rules.
When designing the Rust ORM framework Kova, I followed a clear design principle: there is no kova::prelude::*, and users never have to import any traits when writing queries, mutations, or transactions.
In Kova, whether a node is a table column (User::name), an arithmetic expression, an aggregate function (Count), a scalar function (Lower, Length), a window function, or a JSONB path, every syntax node is uniformly wrapped inside the inherent method hub Node<T>. Behind the where clauses on Node<T> sit TypedNode::Output for computing output types, alongside empty contracts governing syntactic roles (such as CanAssignment, CanDistinct, and CanWindow) and data-type capabilities (such as CanMath<X>, CanString<X>, and CanPgJsonb<X>).
Here is a PostgreSQL query that shows this mechanism in action:
use kova::dsl::func::{Count, Length, Lower, Window};
let rows = client
.select::<Order>()
.inner_join::<User>(Order::user_id.eq(User::id))
.columns((
// 1. Scalar function capability transition: Lower preserves text capabilities; wrapping it in Length shifts Output to an integer, directly unlocking .add()
Length(Lower(User::name)).add(10_i64),
// 2. Aggregate and window structural gating: only aggregate nodes have the .distinct(), .filter(), and .over() inherent methods
Count(Order::id)
.filter(Order::is_active.eq(true))
.over(Window().partition_by(Order::user_id)),
))
.filter(
// 3. Static switching for JSONB operators:
// .json_path() (`->`) preserves the CanPgJsonb contract, allowing a chained .json_delete() (`-`);
// once .json_path_text() (`->>`) is called, Output shifts to plain String,
// all JSONB methods disappear on the spot, and string regex matching .imatches() (`~*`) becomes available
User::profile
.json_path("account")
.json_delete("legacy_token")
.json_path_text("email")
.imatches("^[a-z0-9._%+-]+@rust-lang\\.org$")
)
.load_in::<(i64, i64)>()
.await?;Aside from importing a few SQL function constructors as needed, the entire snippet contains zero trait imports. When holding an ordinary column like User::name, aggregate-only methods such as .distinct() or .over() simply do not exist on it. And as soon as .json_path_text("email") extracts a JSONB node as plain text, every JSONB method disappears with it, cutting off any possibility of chaining another .json_path("...") afterward and blocking invalid SQL like col ->> 'a' -> 'b' at compile time.
Combining the context parameter <X> from the first post with these backstage contracts brings an additional benefit.
Because Kova's data-domain contracts (CanMath<X>, CanString<X>, and others) carry the context parameter <X>, when you bring third-party types like Decimal or Url into your application service, you only need to add two empty trait implementations paired with your AppCodec:
impl CanMath<AppCodec> for Decimal {}
impl CanString<AppCodec> for Url {}With those two lines, Decimal columns in your table models automatically gain numeric and aggregate capabilities like .add(), .increment(), and Sum(), while Url columns gain text processing capabilities like Lower() and .like(), behaving identically to built-in types.
Looking back, use xxx::prelude::* became widespread across the Rust ecosystem because splitting methods into separate extension traits by feature is the easiest path for library authors, even though it offloads the burden of memorizing categorization ledgers and writing manual imports onto every caller. By funneling the public surface through a lightweight inherent method hub, paired with output-type deduction and node-role contracts inside where clauses, we lock the combinatorial complexity of the types completely inside the library. Traits act as contracts guarding the backstage, while methods act as capabilities welded to the type's surface. When a user takes any node in application code and presses ., the methods that belong there appear naturally, and out-of-bounds methods never show up.
In the next post, we will turn to another common issue in Rust generic design, error[E0119]: conflicting implementations of trait: how to resolve trait implementation conflicts when a single method needs to accept both arbitrary external values and internal syntax nodes, without splitting it into separate method names.
The architecture discussed in this series comes from Kova, a compile-time type-safe Rust ORM with deep native support for PostgreSQL and SQLite, no query macros, no trait imports, and flat builder types. See the GitHub repository for the full implementation.