How is this legal?

pub struct Foo<T> {
    t: T,
}

impl Foo<u32> {
    pub fn a(&self) {}
}

impl Foo<()> {
    pub fn b(&self) {}
}

This code appears to compile. Yet, it confuses me that on a generic, when there are different generic parameters, wee can have different implemented functions. Is there a name for this 'feature' ?

Foo<u32> and Foo<()> are different concrete types. There's no name specifically for allowing this as far as I know.

6 Likes

See this post of mine:

2 Likes

One typical example of this is types like

pub struct HashMap<K, V, S = RandomState> { /* private fields */ }

which comes with several impl blocks, and some of them are only defined for the S = RandomState case (such as e.g. HashMap::new).

In C++ this is called explicit specialization, but in Rust the term "specialization" usually refers to overlapping specializations, which C++ supports but stable Rust does not.

In any case, the ability to customize different instances, or sets of instances, of a generic type adds quite a bit of expressive power to generics.

impl AsRef<String> for Box<String> { ... }
impl AsRef<char> for Box<String> { ... }

I think this is a typo in your linked post, second line should be?

impl AsRef<char> for Box<char> { ... }

Very helpful though, nice post :+1:

1 Like

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.