How to Avoid Generic Structs?

⚓ Rust    📅 2025-12-04    👤 surdeus    👁️ 1      

surdeus

I had read that it’s better not to bound structs, but I wonder how? I want :thread: Stringlet to be type safe. It has four slightly different variants with varying optimisations. Since I can’t have an enum as generic marker, I went for marker structs. Each variant has slightly different characteristics, which I implemented on a Config trait. (All done in lib.rs through quite a big macro.)

E.g. if the marker is Slim, SIZE is limited to 0..=64 (because that uses an optional 6-bit UTF-8 niche.) And LEN = 0, because this variant doesn’t need a length byte.

Whereas if the marker is Var, SIZE is limited to 0..=255, because it adds one byte for the length. I put that byte into an array of LEN = 1 to make it easy to create variant-agnostically. Alas const generics are still quite rudimentary, so I couldn’t find a way to calculate LEN or get it from Config. So that’s another generic parameter.

Now this is hidden behind type aliases Stringlet<SIZE>, VarStringlet<SIZE>, TrimStringlet<SIZE>, and SlimStringlet<SIZE>. So all would be fine – except if you want to use them generically. In that case you have to replicate all these generics on your side.

That is quite an awful burden! OTOH I can’t see a way to avoid it, if I want only valid parameter combinations to compile.

Is there a cleaner solution?

1 post - 1 participant

Read full topic

🏷️ Rust_feed