Restricting generics to just a few types

⚓ Rust    📅 2025-08-06    👤 surdeus    👁️ 4      

surdeus

Suppose I have

struct SomeStruct<T> {
    inner: Vec<T>,
}

At least for the time being, I only need T to be one of i64 or String.

Getting the generic T to satisfy trait bounds can be quite a battle. For example, using rkyv, it has to satisfy all sorts of bounds from inside that crate.

To save myself some trouble, I'd like to just tell the compiler "hey, this is only a i64 or String, it can't be anything else", but I don't know of any way of doing that. Here are some things I have considered:

  • The standard advice seems to be to use an enum, but I think that's wrong here as then every element of the Vec would be an enum. This is not what I want, I want the Vec elements to be the same fixed type.
  • I could promote SomeStruct to a trait, and just write a few specific structs with i64 or String. This looks better in this example than it does in real life where I have at least two parameters that I need to do this for. The other problem is that this seems like a temporary solution, because implementing generics for that trait is going to run into some of the same issues.
  • I could write a macro to generate impl of the appropriate method for each case, but this seems pretty elaborate for something so simple.

I feel like there's a more standard way of doing this that I'm missing, any ideas?

6 posts - 5 participants

Read full topic

🏷️ Rust_feed