this post was submitted on 10 Sep 2023
8 points (100.0% liked)

Rust Programming

8176 readers
10 users here now

founded 5 years ago
MODERATORS
 

I want to do basically this:

struct MyStruct < T> {
    data: T
}

impl < T> for MyStruct < T> {
    fn foo() {
        println!("Generic")
    }
}

impl for MyStruct < u32> {
    fn foo() {
        println!("u32")
    }
}

I have tried doing

impl < T: !u32> for MyStruct < T> {
    ...
}

But it doesn't seem to work. I've also tried various things with traits but none of them seem to work. Is this even possible?

EDIT: Fixed formatting

top 5 comments
sorted by: hot top controversial new old
[–] [email protected] 6 points 1 year ago (1 children)

What you are looking for is called specialization.

It is currently unstable and incomplete, which means you can activate it by adding the macros #![feature(specialization)] and #![allow(incomplete_features)] at the beginning of the file. But you have no guarantee that it will work the same way on the next version of rust.

[–] [email protected] 3 points 1 year ago

Yeah, that seems like it would work! Unfortunately I can't use unstable features. I'll keep it in mind for other projects though.

[–] [email protected] 1 points 1 year ago* (last edited 1 year ago) (1 children)
[–] [email protected] 2 points 1 year ago* (last edited 1 year ago) (1 children)

I'm sorry, no wonder you are lost, so it made no sense when you wrote this comment, lemmy deleted everything between the "less than" character and ">". I had to change them for "<" in order for them not to get deleted.

[–] [email protected] 4 points 1 year ago

lemmy deleted everything between the “less than” character and “>”.

Lemmy also escaped the ampersands in their comment's link 😉

Isn't broken sanitization great!