vlang / rfcs

RFCs for changes to V

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Wrapping Arithmetic Operators for Integers: +~, -~, *~ or /~

igotfr opened this issue · comments

Wrapping Operations for Integers
These operations have guaranteed wraparound semantics. Failing when the result cause overflow

  • +~ (wraparound addition)
  • -~ (wraparound subtraction)
  • *~ (wraparound negation)
  • /~ (wraparound multiplication)

Example:

u8(129) +~ u8(129) // error

@Cons-Cat says:
Imho, the use case for guaranteed wrap-around semantics is niche and it could be simpler to handle this with special structs in the standard library named something like math.WrapI32, math.WrapU32, etc. (or possibly a generic struct, although I'm not sure how to make that work for this case off the top of my head). The operator overloading rules of V might make this cumbersome, since you wouldn't be able to compile val := math.WrapI32(1) + 1, though, because you can only + a non-primitive type (like a struct) with a value of the same type. Nevertheless, I feel like that approach is most in line with the current direction of the language, personally.