4 ms·
Rust ranges aren't types. In Ada you can specify a type like: type Temperature is range -100 .. 300; -- in Celsius, operating range for an aircraft or system
by Jtsummers 3y ago
Rust ranges aren't types. In Ada you can specify a type like:
type Temperature is range -100 .. 300; -- in Celsius, operating range for an aircraft or system perhaps
You cannot assign anything outside that range to variables of that type, if the value is known at compile time it won't compile otherwise you get a runtime error (unless you disable checks). You cannot assign an arbitrary integer variable's value (that holds a value in that range) into a variable of type Temperature, you have to cast it.
T : Temperature := 500; -- won't compile
...
T : Temperature;
N : Integer := 50;
...
T := N; -- won't compile
T := T1 + T2; -- two other temperatures; runtime error if sum is outside -100 .. 300
If you want a subtype range you might do something like:
type Days is (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday); -- an enumeration
subtype Weekdays is Days range Monday .. Friday; -- ranges are inclusive in Ada
Now you can have a variable of type Days and try to put its value into a variable of type Weekdays and you'll get a runtime error if it's Saturday or Sunday. And you can use these for array indices. These are actual arrays, not dictionaries, so you don't get the performance penalty of a map/dictionary (though generic maps are also available):
Schedule : array (Weekdays) of ...; -- fill in with some useful type; Weekdays is the index range
D : Days;
W : Weekdays;
...
W := D; -- will compile, may error at runtime
D := Saturday;
W := D; -- will error at runtime
W := Sunday; -- won't compile
W := Monday; -- will compile
Schedule(W) := ...;
- pjmlp 3y agoAs an addendum, this is something that most Pascal derived languages also support, Object Pascal, Mesa, Modula variants, (with exception of Oberon and its linage), and sadly many associate only to Ada.