Pre-RFC: Custom suffixes for integer and float literals

Thank you everyone for your response and critique!

I’ll wait a bit more for this discussion to unfold further and at the end of this week will try to write “take 2” for this proposal. Currently my thoughts are:

  • We need this feature, Duration::from_secs(2) + Duration::from_millis(200) is annoying both to write and read.
  • We need clear imports for custom literals.
  • But we probably don’t want to create a separate namespace for suffixes.
  • Feature should be extensible to string literals prefixes/suffixes.
  • Custom literals should be usable in match statements and ideally with runtime values.
  • Regarding 1s vs 1_s I think feature should support both, maybe with a recommendation to use 1_s in guidelines (excluding exceptions like complex numbers and quaternions)
  • For compound units (e.g. “m/s^2”) looks like the best approach will be to use suffixes which accept additional arguments, something like 2.3_si[m/s^2] (I am not sure if we need an explicit ! here, see further). Here you’ll import custom si suffix which will be able to support various units.

So here my rough thoughts: I think solution is to use macros for custom literals. Reasons are:

  • they will not conflict with variable names and naming conventions
  • macro output can be used in match statements without any problems
  • procmacros will allow more flexibility in future

In other words 1s will be desugared into s!(1) and 2.3_si[m/s^2] to si!(2.3, "m/s^2"). Because in this design custom literals can only be defined by a macro we can omit !. If user will wants to use those suffixes on runtime values, he can write: s!(var) or with postfix macros var.s!(). Macros which define custom suffixes should be marked with #[cusom_suffix] attribute. Though we will need a proper macros import system.

Unresolved questions:

  • Details on how macros will look internally. Should they accept expr or something like int_literal/float_literal?
  • Do we want a generic way to define set of sufixes without code duplication? (e.g. u1-u256)
3 Likes