Numeric ranges #11579
Replies: 3 comments
-
There is a way to enforce that a field is never constructed with a value it should not hold using the optional return constructor pattern. The constructor function for a struct OddInt would be: struct OddInt {
i int
}
fn odd_int(i int) OddInt? {
return if i & 1 {OddInt{i}} else {none}
} This forces the programmer to handle |
Beta Was this translation helpful? Give feedback.
-
Hmm, it feels quite complicated. The asserts are intended for against rare bugs. Once these bugs are chased out, what remains is simple code (plus those asserts, but one learns to skim over them). Constructs like above would remain even in perfectly debugged code, and decrease readability. C++ allows lot of similar tricks, but IME they are not worth the trouble. |
Beta Was this translation helpful? Give feedback.
-
If asserts can be stripped out, the test for |
Beta Was this translation helpful? Give feedback.
-
If V will support numeric ranges (number can have values from 2 to 50), here's possible syntax which does not require new keywords, arcane concepts or use of cryptic prefixes/suffixes.
It is possible to go further this way, and add runtime checks (used in debug mode):
Combination of compile time and runtime checks:
Similarly, pointer values could be restricted, without overdoing it with crazy combinations of prefixes.
Here are few possibilities:
The compiler could check that a desired property is preserved. E.g if I try to assign nullable pointer to non-nullable, there has to be a null check before. The compiler would refuse it otherwise.
Possibly, this form could be also used to restrict types in generics.
Beta Was this translation helpful? Give feedback.
All reactions