How does Rust look for Associated functions and constants?

Hello, everyone.

As the title says, I'm quite curious about the order in which Rust finds associated functions and constants.

For example, in the case of the code below, Rust will look for inherent associated functions and constants first, then go over traits.

I read document about it from here.

But I'm not sure the document says associated functions and constants as well.

So, can anyone teach me about the order?

Example of impl detection

pub struct ImplDetector<T>(std::marker::PhantomData<T>);

pub trait EqualType<T> {
    const IS_EQUAL_TYPE: bool = false;
    fn is_equal_type() -> bool { false }
}

impl<T> EqualType<T> for ImplDetector<T> {}

impl<T> ImplDetector<(T, T)> {
    pub const IS_EQUAL_TYPE: bool = true;
    pub fn is_equal_type() -> bool { true }
}

fn main() {
    struct A;
    struct B;

    assert!(ImplDetector::<(A, A)>::is_equal_type());
    assert!(!ImplDetector::<(A, B)>::is_equal_type());

    const _: () = {
        // Why does it work?
        assert!(ImplDetector::<(A, A)>::IS_EQUAL_TYPE);
        assert!(!ImplDetector::<(A, B)>::IS_EQUAL_TYPE);
    };
}

(Playground)

1 Like

RFC 195 contains a description of the lookup algorithm for an associated item.

5 Likes

Some notes on reading RFC 195 -- or RFC 132 for associated functions.

  • Unqualified paths that lead to a type are normalized to <...>:: ("TYPE_SEGMENT prefix").

  • Both RFCs were written when dyn Trait was just spelled Trait, so there was an inherent ambiguity between whether Trait refers to the trait or to the type (the trait object type, or what we'd calll the dyn Trait type today). You have to keep that in mind when reading the RFCs for many things to make sense (and it's still somewhat confusing).

  • There are some other oddities around inherent methods on trait objects.

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.