Skip to content

Instantly share code, notes, and snippets.

@peter-kehl
Last active March 28, 2024 15:07
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peter-kehl/3d5b480dc563243e1a240766893fb41a to your computer and use it in GitHub Desktop.
Save peter-kehl/3d5b480dc563243e1a240766893fb41a to your computer and use it in GitHub Desktop.
Rust Const Generics

Presentation on Const Generics as of 1.50.0 stable and 1.52.0-nightly

Challenges

  • Beware no, or misleading, documentation
  • Syntax may seem arbitrary:
    • Need ::< turbofish at some places, ordinary < elsewhere.
    • Need {...} curly brackets around some const generic parameter values, not around others.
    • Some error messages feel like going in circles.

Learning

  • If your constant generic parameters are not integer/char/boolean, don't downgrade your domain.
    • Use #![feature(const_generics)] to allow structs and enums as const generic parameters.
    • Such struct/enums need #[derive(PartialEq, Eq)] (or their implementation).
    • Trust nightly.
  • Even though the purpose of (const) generics is to reuse code, the actual const generics code is repetitious. You'll have to repeat where clause in any impl that involves a type with const generic parameter, if the const generic parameter affects size of any field(s).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment