Skip to content

Inconsistency in trait item resolution between Box<Trait> and impl Trait #41221

Open
@petrochenkov

Description

@petrochenkov

Consider this example:

#![feature(conservative_impl_trait)]

// use m::Tr;

mod m {
    pub trait Tr {
        fn method(&self) {}
    }
    impl Tr for u8 {}
    
    pub fn dynamic_tr() -> Box<Tr> { Box::new(0) }
    pub fn static_tr() -> impl Tr { 0u8 }
}

fn main() {
    m::dynamic_tr().method(); // OK
    m::static_tr().method(); // ERROR: no method named `method` found for type `impl m::Tr` in the current scope
}

Here we are trying to call methods of traits that are not in scope.
Typically such methods are not resolved, but there's an exception - trait objects.
Trait objects are magic - when you call a method of Trait on a value of type Trait then Trait is automatically considered in scope (or maybe this method is treated as inherent, I haven't looked how exactly the implementation works). This is the reason why m::dynamic_tr().method() works. Even if this is a special case, it's a reasonable special case - if you have a value of type Trait in hands, you typically want to call some trait methods on it and it would be a nuisance to require Trait imported in scope for this.
I don't know what RFC or PR introduced these exact rules, but the fact is that they are used in practice.

All the logic above is applicable to impl Trait, but this special case doesn't apply to it and m::static_tr().method() reports an "unresolved method" error.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-resolveArea: Name/path resolution done by `rustc_resolve` specificallyA-trait-systemArea: Trait systemA-type-systemArea: Type systemC-bugCategory: This is a bug.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.T-typesRelevant to the types team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions