-
Notifications
You must be signed in to change notification settings - Fork 18.4k
Description
Context:
When certain data types are known to only have a limited set of values, then it is only possible to test for these dynamically in the current Go version.
It should be possible for incompatible types to be tested statically at runtime.
Proposal:
I can think of two ways to specify a constraint on the possible values of an integer type:
- as an enumeration (has been proposed in other proposals, won't repeat here)
- as a range
E.g.
type MONTHS range 1 ... 12
type DAYSOFMONTH range 1 ... 31
subtype DAYS_OF_FEBR of DAYSOFMONTH range 1 ... 28
subtype DAYS_OF_LEAP_FEBR of DAYSOFMONTH range 1 ... 29
when I receive a value of type DAYSOFMONTH
then I would like to test if it is valid for a subtype.
E.g.
var birthday DAYSOFMONTH
birthday := 14
if birthday in DAYS_OF_LEAP_FEBR { ... }
This concept exists in the Ada programming language.
There needs to be a conversion capability to convert non-constrained integer types to and from constrained integer types (range or enumeration).
This is useful when decoding and encoding between binary data received over a communication link and logical data.
E.g.
var b1 int
var b2 int
var f DAYSOFMONTH
b1 := 14
f := b1 // potential out-of-range
b2 := f // should be safe
conversion from constrained types to unconstrained should not be a problem
conversion from unconstrained types to constrained can result in an error.
Assignments that can cause an out-of-range condition need to be accompanied with an error assignment. The compiler can enforce the use
E.g.
var err error
f, err := b1 // when out-of-range, f is assigned Nil