Skip to content

Support use Trait::method and/or Type::method? #1995

Open
@Rufflewind

Description

@Rufflewind

Currently Rust doesn’t support any of the following:

// Example A
use Default::default;
use f64::sin;

This means one can never write default() or sin(3.14) without qualification as individual methods can never be imported in isolation. (Of course, one can also write 3.14f64.sin(), but not everyone is a fan of reverse Polish notation; this could be a deterrent for numerical users of the language.)

One workaround is to create a prelude-like module with wrappers:

// Example B
pub fn default<T: Default>() -> T { T::default() }
pub fn sin(x: f64) -> f64 { f64::sin(x) }

This is a lot of boilerplate. Perhaps it would useful to make Example A “just work”?

For static methods, the intent is pretty clear: it would enable

static_method(arg1, arg2, …)

This would be just a shorthand for calling Trait::static_method. It won’t work if Self is ambiguous.

For non-static methods, it’s not obvious what use Trait::method would do. Which among these would it enable? (Either or both?)

method(obj, arg1, arg2, …)
obj.method(arg1, arg2, …)

@petrochenkov mentioned:

Adding use Trait::AssocItem; should be simple, it mostly needs motivation and decision.
use Type::AssocItem; is not possible with current organization of compilation stages.

This issue was motivated by @HadrienG2’s Experience porting a simple MC simulation to Rust.

(The issue was moved from rust-lang/rust#41453.)

Metadata

Metadata

Assignees

No one assigned

    Labels

    T-langRelevant to the language team, which will review and decide on the RFC.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions