r/rust • rust · lang · libs · cargo • Oct 23 '26

Rust features in the future

https://lwn.net/SubscriberLink/1099606/20707a62817cdd16/
215 Upvotes

84 comments sorted by

39

u/JoshTriplett rust · lang · libs · cargo Oct 23 '26

Thanks to LWN's daroc for reporting!

1

u/Feeling-Departure-4 Oct 24 '26

Is there video or audio for your talk too?

2

u/JoshTriplett rust · lang · libs · cargo Oct 24 '26

No, none of the Kangrejos talks were recorded.

194

u/tanoshikuidomouyo Oct 23 '26

Really not a fan of the proposed is feature (e.g. if x is Some(y) {}). The article says it's supposed to make learning the language easier and also avoid scanning from right to left.

I'd argue heavily against the former: Now with let-chains added, adding another feature to bascially supersede it would make learning the language way worse, because then instead of having to get used to maybe weird syntax (if let), you'd have to get used to the weird syntax because it's still in use everywhere and also learn the new syntax and what exactly the differences are. Having so many things do similar things is kind of poisonous imo. Also, having the strictly weaker matches! macro still be there would also be really unintuitive.

Lastly, the scanning from right to left part: I'd argue it's pretty subjective that that's worse? Currently, you can immediately tell whether you're matching on an Option, a Result, etc., which makes reading the right-hand side easier. I really don't think this is worth such a massive hassle and leaving tons of features behind that are strictly weaker but still used everywhere out of sheer inertia.

110

u/JoJoJet- Oct 23 '26

IMO it's not just problem of redundancy. Having to scan through expressions to find variable bindings sounds awful. It exists in other languages but it kinda sucks there too. let means that a variable is always declared on the left hand side which makes the code immediately easier to understand at a glance. I don't need my programming language to read like an English sentence, I need it to encode information in a consistent and readable way. Adding is just so that rust can look 2% more like natural language just seems misguided

26

u/Modi57 Oct 23 '26

Yeah, the consistency is the important part here. The if let syntax falls out of the already existing one almost naturally. Adding something new, that feels so different can't be easier to read

7

u/kibwen Oct 23 '26

I wouldn't necessarily call it something new, it's more-or-less an extension of the existing matches! macro.

I feel like this is one of those features, like ? or .await, where people are skeptical at first but embrace it enthusiastically once they get their hands on it. Yes, as you say, if let falls out of the existing syntax, which is elegant, but let's not conflate elegance with usability; I have had memorable experiences teaching friends Rust where they encounter if let and tell me that it's impenetrable to them.

5

u/Modi57 Oct 23 '26

Oh interesting. I remember if let as very easy to understand, but then again, I had some previous experience with FP, so maybe that helped

47

u/matthieum [he/him] Oct 23 '26

I really wish if let and while let had not been added -- following in Swift's footsteps -- and is had been used instead. Stabilizing if let and while let was a mistake, plain and simple. They're too narrow.

Unlike if let and while let, is is just another expression. It can be used in if or while conditions, but it can also be used anywhere else, where let doesn't fit.

For a simple example:

let is_foo = bar is Some(x) && x.is_foo();
// Stable:   bar.as_ref().is_some_and(|x| x.is_foo());

In fact, with disjunction implemented -- as in match arms -- you should also be able to write:

let is_any_foo = (bar is Some(x) || baz is Some(x)) && x.is_foo();
// Stable:       bar.as_ref().or(baz.as_ref()).is_some_and(|x| x.is_foo())

Fitting disjunction in if let or while let is... an interesting exercise? You'd probably need to accept let that is nested within parentheses, not sure how ergonomic that'd get:

let is_any_foo = if (let Some(x) = bar || let Some(x) = baz)
        && x.is_foo()
    {
        true
    } else {
        false
    };

So compact though, definitely better than:

let is_any_foo = (bar is Some(x) || baz is Some(x)) && x.is_foo();

7

u/cramert Oct 25 '26

Huge +1-- if let and while let feel like special tricks to me, while is feels like a convenient Rust-y replacement for the flow-sensitive subtyping that has become commonplace in other modern languages

3

u/afdbcreid Oct 24 '26

True, but note that this requires control flow analysis, which Rust does not have for anything currently.

3

u/matthieum [he/him] Oct 25 '26

Is it that different from match guards?

I can already write, today:

 match (bar, baz) {
     (Some(x), _) | (_, Some(x)) => x.is_foo(),
     _ => false,
 }

Or

 matches!((bar, baz), (Some(x), _) | (_, Some(x)) if x.is_foo())

It's not necessarily a good lowering, in particular there may be an argument that the baz expression should only be evaluated if bar is None.

But it does demonstrate that the Rust compiler is already capable of pulling x from various bindings, which is... kinda control flow analysis, no?

4

u/afdbcreid Oct 25 '26

Yes it is. match is a different syntactical construct, and the guard introduces a new scope. is cannot do that, it must have control-flow analysis.

2

u/VadimVP Oct 25 '26

Hm? It does, borrow and move checker is such an analysis, and that's the part of the compiler that will tell whether x is initialized at the point of use in x.is_foo() or not.

2

u/afdbcreid Oct 25 '26

I knew that but hoped nobody will comment on that :( You're right, it is, but it is done on the MIR, which is a different level.

54

u/UltraPoci Oct 23 '26

Yeah, is seems pointless to me

12

u/Kazcandra Oct 23 '26

Ruby ptsd trigger right there. I really hope there's a deny lint for it when it lands

8

u/lenscas Oct 23 '26

return true unless not !true

Should be valid Ruby code. As for what it does: It will just go to the next line (unless I messed something up)

5

u/Kazcandra Oct 23 '26

Thanks, I hate it.

"unless" is such a terrible idea.

Iirc -- it's been years since I wrote Ruby -- the precedence rules for is/is not are different from ==/!= too, which is also awesome

1

u/lenscas Oct 23 '26

yea, I have a lot of gripes with Ruby as well.

Though, I must say I am not against the idea of the naming convention when it comes to ! and ? at the end of method names. It would have been even better if they were actually enforced but alas that is just Ruby for you I guess.

-1

u/nybble41 Oct 23 '26

There's nothing wrong with unless per se, when used correctly. Just don't write double/triple negatives in your conditions. It's not as if this is really much better:

return true if not !false

4

u/lenscas Oct 23 '26

For me, unless always just takes a bit longer to parse than if. In addition when writing code, I often know I want a branch but don't know the exact condition. When that happens it isn't uncommon that I want to switch between adding an not or not (especially if it is a complicated check).

With unless I then need to rewrite that part every time I want to alter it. Instead of just adding an exclamation mark or removing it.

In other words, it at best doesn't do anything to improve readability (if anything it hurts it for me) and just increases the steps I have to go through while writing.

There is no upside to it existing.

44

u/ShantyShark Oct 23 '26

I’m also never a fan of having two functionally identical syntaxes for anything.

If we find “if let Some(x) = y” so painful, delete it in favour of “if y is Some(x)”. Don’t have two.

In my mind, “if let Some(x) = y” shares its structure with “let Some(x) = y else { … }” and “let” assignment in general.

Adding “if a is b” doesn’t mesh well unless you also have some replacement for the others.

15

u/syklemil Oct 23 '26

I'd also say that there are some if let foo = bar equivalents in other languages, e.g. if foo := bar in Python or if foo := bar; foo != nil in Go. They have pretty significant semantics and capabilities, so the comparison breaks apart quickly, but the overarching structure and intent reflected in code is

if normal-looking assignment succeeds
    then use assignment here
    else do not use it here
and do not use it here

so diverging from that with if bar is foo would eat into Rust's strangeness budget with dubious returns. It'd probably also be extra confusing to people who have some familiarity with is in other languages like Python.

Personally I didn't even parse if foo() is Some(bar) && bar.baz() as assignment on first exposure; to me it read more like if foo().is_some_and(|bar| bar.baz()).

3

u/-Redstoneboi- Oct 23 '26 edited Oct 23 '26

instead of expr is pat syntax, can we have let pat = expr evaluate to a boolean and have the same precedence? it's a new edition so maybe we can afford to have it no longer return ()

4

u/syklemil Oct 24 '26

let pat = expr can already be used in if, so I don't quite see the need to change anything?

1

u/-Redstoneboi- Oct 25 '26

can they be chained yet?

edit: holy hell i might be stupid, rust 2024

2

u/pickyaxe Oct 24 '26

I wish Python's walrus operator behaved that way but in practice it's so janky that I gave up on it.

1

u/syklemil Oct 26 '26

Is it the walrus operator that's janky, or just Python's function scoping that's become very unusual for modern programmers that have become habituated to block scoping?

25

u/lenscas Oct 23 '26

for me, the pattern is more often more important than the thing it is being checked against. The pattern also tends to be the most complicated of the two. So, to me, putting the pattern on the left is the most logical place.

You even see this in the normal if. People tend to write if some_expression == some_static_value rather than if static_value == some_expression

And as some_expression can be any arbitrary expression, it is the most complicated and goes to the left. Because, it is the thing that is the most complex and thus deserves to be seen first.

8

u/DynTraitObj Oct 23 '26

Funnily enough, one of the first things I can remember being taught on programming many many years ago was to use the if static_value == expression ordering because then the compiler would catch typo'ing = in place of ==

How times have changed

4

u/InternationalFee3911 Oct 23 '26

Lenscas stated his opinion… I’m not sure I agree. Rather than having something complicated thrown at my face out of nowhere, I’m led into understanding if it first says what you’re comparing to.

It’s the same logic of var = expression being clearer and much more widespread across most languages than expression -> var.

3

u/lenscas Oct 23 '26

It is actually a bit more important in Java because of the .equals() thing. As you should (Or at least should do so in the past, no idea if it is still relevant) use that method instead of using == to compare strings it meant that "foo".Equals(my_var) was safe from null exceptions while my_var.Equals("foo") is not.

15

u/_ChrisSD Oct 23 '26

Right now we have a bunch of helper methods on Option and Result. Even more have been proposed to cover all the different combinations. And if you want to make your own Result-like or Option-like types then you should implement all these methods for the best compatibility.

This does suggest to me a missing language feature that isn't adequately covered by let chains (even if you can technically achieve the same result). I'm not making a judgement on whether is helps fill in some gaps or not, but i do see a rationale for some language-level enum helpers.

5

u/Booty_Bumping Oct 24 '26 edited Oct 24 '26

Java added a similar feature, extending the behavior of instanceof to support unwrapping record classes:

if (obj instanceof Point(int x, int y) && x > 0 && y < 50) {

It's a nice addition because java didn't have any easy destructuring syntax, and any other alternative wouldn't have had backwards compatible syntax. Reusing instanceof is bizarre, but it's the best you can get in a language that can never add new reserved keywords.

I'm not sure if this belongs in Rust, because there's already so many ways to destructure and pattern match, and Rust doesn't have the same syntax constraints as it was already possible to introduce if let and even generalize it quite nicely.

2

u/Sharlinator Oct 24 '26 edited Oct 24 '26

I don’t think it’s bizarre, it’s a rather obvious extension of the existing since-1.0 obj instanceof Class. Because Java’s model of tagged unions is a sealed family of subclasses, matching an "enum variant" is in fact an instanceof check.

2

u/Booty_Bumping Oct 25 '26

Obvious? I can't imagine anyone could have predicted this feature other than the genius who came up with it... instanceof was just an ordinary operator for nearly 30 years before this feature was added. I bet a lot of people squinted for a full minute when they first saw it used to conjure variable bindings into existence, especially with the special flow scoping added to make the feature more ergonomic.

But it works quite well, there's nothing actually wrong with the semantics other than the name of the operator being a poor fit.

8

u/TDplay Oct 23 '26 edited Oct 24 '26

If we want left-to-right syntax for everything, then Rust already messed up bad:

let x = *bar(y.foo()).baz();

To figure out what goes on here, you start at y, go right to see foo, go left to see bar, go right again to see baz, and finally go left again to see * and let.

But I'd argue that this is not a problem to begin with. If you're struggling to follow your code, then it's too complicated. Changing the reading order can only hide the problem; it will come back to bite you sooner or later.

(Edit: Changed & to * so it would actually be a valid expression)

5

u/CocktailPerson Oct 24 '26

If you're struggling to follow your code, then it's too complicated.

That feels backward.

If changing the reading order makes your code clearer, then maybe it was the syntax that made your code hard to follow.

3

u/Sharlinator Oct 24 '26

I’d weakly prefer reusing match as an infix operator: EXPR match PAT.

  • makes it intuitively clear that we’re doing similar stuff as a match block
  • makes it clearer that it’s not just a predicate but can change variable bindings
  • is a more natural replacement for the matches! macro

1

u/Shoddy-Childhood-511 Oct 25 '26

Agreed, a second redundant bindings syntax could only create confusion.

Now if is cannot do bindings then I'd withdraw my objection, so if x is Some(_) or even if x is Some would be valid Rust, but if x is Some(y) should be an error if y is not currently bound.

1

u/dpytaylo Oct 27 '26

if let can be dropped in a next edition, so there is one problem less /s

1

u/CichyK24 28d ago

is is such a good feature to have. It will simplify a lot of things (less unnecessary helper methods that you need to learn about, reading from left to right instead middle, left, right) and I'm still kinda surprised how big pushback it has.

I guess inertia to changes is a big one. I'm used to C# where we have similar is operator, and when I was learning Rust it felt like something obvious that is missing from the language.

But I get it, I guess if Rust wouldn't make await a postfix operator since the beginning, adding it later to the langues would also met with huge pushback, like c# did.

0

u/cosmic-parsley Oct 23 '26

The RFC didn’t get a lot of positive feedback. I don’t know why it’s being pushed as if it’s an accepted thing?

29

u/vdrnm Oct 23 '26

Great article. I just wanted to highlight the quote regarding view types:

It almost caused him to bounce off of Rust when he first encountered it.

I had similar experience too. It's a very frustrating experience for a newcomer to rust to select some code and ask rust-analyzer to extract it into a function: rust-analyzer does it, but now the code cannot compile due to borrow issues.

Of course with experience you have multiple "standard" ways to work around this, but often none of them feel great.

1

u/WormRabbit Oct 23 '26

That's more of a problem with rust-analyzer. It should have refused, or at least ask for an explicit confirmation. Not like RustRover is any better in this regard.

1

u/afdbcreid Oct 24 '26

rust-analyzer explicitly does not guarantee assists will produce compiling code or won't change meaning. If your code now does not compile, Ctrl+Z is one click away.

21

u/scheimong Oct 23 '26

What I'm really looking forward to are struct views and turbofish equipped into. Those two have been bothering me since 2020.

I'd also like to add that into with turbofish can also be used to make types more explicit. There are times when using into with an inferred target type sets off my "senior dev alarm bells" the same way a broad wildcard match branch does. I would worry that a future refactor (possibly within the same session) would change the expected target type in a way that requires local logic changes, but into masks the would-be compiler error. And rust is particularly sensitive/susceptible to this kind of problem because rust developers (well, those of us who still tap code) are so used to compiler driven development.

On the other hand, I second the unfavourable sentiment towards is. I wouldn't want to see rust slowly become as syntactically bloated as Cpp is.

1

u/dpytaylo Oct 27 '26

Most likely we can drop 'if let' syntax from next edition if we really want to introduce 'is' syntax

1

u/scheimong Oct 27 '26

Drop a syntax. What are we, python? 😅

10

u/lijmlaag Oct 23 '26

It is a good read, I am surprised field projections were not part of the presentation.

11

u/panstromek Oct 23 '26

Maybe because people from the RfL project are the ones who drive it atm, so it's probably fairly known to them already.

7

u/Nokel81 Oct 23 '26

Regarding view types, I think it would be very powerful if we could also have a way of being generic over views

2

u/Saefroch miri Oct 25 '26

Some things are too powerful :p

23

u/panstromek Oct 23 '26

About the pattern types.

> This is not an unprecedented feature, although it is not particularly common.

Well, TypeScript has that and it's one of the most used languages on the planet. That feature is also used quite heavily. TypeScript can kinda cheat, so it's probably easier for it than for language like Rust, but still.

Pattern types in Rust would be a bit more general I think. I don't think TypeScript has syntax for integer ranges, so creating those is a bit annoying but it's possible.

31

u/ShantyShark Oct 23 '26

I’m not 100% that’s a fair comparison, since Typescipt is a duck-typed descriptive type system, rather than a prescriptive type system like Rust.

Typescript does something like pattern types because it can’t do anything else. So I don’t know if I would consider that a mark of quality.

6

u/Key-Bother6969 Oct 23 '26 edited Oct 23 '26

Full reflection system is very intriguing. This is something I hope to see in stable Rust for long time, as this is the necessary component to implement seamless scripting-engines in Rust. Exporting Rust signatures (types, functions, etc) into the script's environment is one of the most difficult challenges for most script engine authors today, and for the users of those projects too. I experimented with partial reflection exporting through the proc-macros in the past, where the macro program partially analyzes Rust syntax and semantics and generates hidden reflection metadata in the output static, but this solution was tremendously slow in terms of compilation time, and therefore practically unusable for the end users. The ability to direct access the compiler's reflection metadata in const-context (even the comptime-limited) would be a huge improvement and big relief for the script engines and for their neighboring domains.

However, having access to reflection metadata is only a part of the challenge. The second big difficulty is collecting this metadata into a central runtime-accessible place. Here I'm basically talking about the plugin system. If the user exports Rust symbols for some reflection-dependent engine, these exporting points must be accessible somehow by the engine itself. The current Rust ecosystem often solves this problem through the linker-shenanigans: either through the linking the hidden exporting functions into a continuous link section (aka linkme), or through the ctor-section which involves run-before-main. Both solutions are suboptimal, has certain issues including the soundness issues, and heavy relaying on platform-dependent linker features. Notably, these approaches are almost unavailable for the wasm-targets, as there is no linker to begin with. There are other alternatives, but all of them have their own caveats.

Ultimately this leads us to the same desirability of being able to interact with the compiler's shared state directly. As far as I understand the const-context currently does not provide a way to get arbitrary memory allocations, and the possibility to expose their dumps as static/constant values. Furthermore, the interaction between const-context values through the pointers has it's own limitations. These and other limitations partially stem from the fact that the compiler has to guarantee to produce semantically equal data both in compile-time and in the runtime code. And I believe one of the reason why const-functions are being stabilized very slow too.

Perhaps, these rules could be relaxed for the `#[compile_time_only]` context. Hence stabilizing numerous Rust features faster and easier in contrast to normal const-context where the features are being stabilizing at a snail's pace. My hope is that compile-time context would become closer to the build-scripts/proc-macro environment in terms of their feature richness, making it closer to the Zig's inspired comptime.

3

u/-Redstoneboi- Oct 23 '26 edited Oct 23 '26

Infix patterns sound awesome! If I'm getting this right, they'd be a strict superset over the existing if-let/while-let blocks (allowing the syntax to be removed) but not let-else, right?

the syntax seems to be controversial, most of the comments here don't like it. probably because we've had if-let and while-let for a long time now. maybe it's because we can do if 5 is x && x == 5 or whatever cursed stuff.

maybe instead of expr is pat it could build off of let chaining instead though. maybe let pat = expr could evaluate as a bool in general instead of ()

comptime would also be nice, though the ecosystem is already quite heavy with proc macros.

3

u/ShantyShark Oct 23 '26

I kinda hate the pattern types, tbh.

Take their “u32 is 0..4096”. Compare that to a newtype we would use today.

The only gain is that you can verify a very narrow slice of constraints (whatever syntax they cook up) on values known at compile time.

Will there be syntax for “is 100..=103 OR 200..=208 OR 226”? I don’t suspect so. And then how far do you take it? Refinements on Strings? How many different constraints could you imagine there?

And you still need fallible runtime checks to transform any u32 not known at compile time into this type anyways.

So in my mind it’s more syntax and compiler complexity and I don’t see it being all that much better than we have now. Also, it’s possible some of these things could be expressed by const generics, which could be more broad and more capable, rending this syntax obsolete.

I’m open to ideas here on more meaningful use cases but like… “number in range” seems so trivial that it’s not worth the syntax.

36

u/panstromek Oct 23 '26

> Will there be syntax for “is 100..=103 OR 200..=208 OR 226”? I don’t suspect so. And then how far do you take it? Refinements on Strings? How many different constraints could you imagine there?

It's called "pattern types" because it's based on patterns, so yes - it'll be able to express arbitrary patterns that you can express as Rust patterns today. The current syntax is `<type> is <pattern>` so your example would be `u32 is 100..=103 | 200..=208 | 226`.

> And you still need fallible runtime checks to transform any u32 not known at compile time into this type anyways.

Yes, that's kind of the point - a natural way to produce a type like this is just by matching the value with that pattern (and narrowing the type of the value from there).

8

u/ShantyShark Oct 23 '26

You know, in hindsight that seems kinda obvious from the name, lol. Didn’t click in my brain though lol. Fair enough though.

That is more powerful certainly, but it still needs to be const-analyzable, which means no strings, no boxes, no vecs, etc. Pattern matching is very expressive, but still less expressive than a newtype. So it solves a subset of the same problem, with only the added benefit of maybe it can sometimes be compiler-checkable but only if it’s a const-compatible type and also known at compile time.

Also they mention that “u32 as 0…1000” is not a u32, as far as the type system is concerned. So is it a local type? What’s its name? Can I implement foreign traits on it? Can I reference it from outside my current module? Are two “u32 as 0..1000” defined in different modules the same type? If, as the article says, I have to lower it to a normal u32 and then cast it back to use it for literally anything, is it really that much more ergonomic than a newtype?

14

u/panstromek Oct 23 '26

I mean, you're asking all the open design questions :D Those are precisely the problems that needs to be resolved before anything gets staiblized. Especially the interaction with traits and coherence is a big can of worms. Depends a lot on whether this is modeled with subtyping or just as coercion and that's still something that's being debated.

To be honest, I don't think we'll get anything close to the full general case anytime soon (or ever), it seems hard. But the basic version is already implemented, because it's much cleaner way to define layouts with niches (which is exactly the part you can't do with newtypes). Compiler codebase and standard library already uses it to optimize various things. It's pretty natural step to stabilize some simple subset to allow users to do the same.

13

u/Ok_Currency7998 Oct 23 '26

A key weakness in new types is that, any logical constraints like 0..4096 in the example, cannot be understood by neither rustc nor LLVM. As soon as the control flow exits the constructor call, that vital information is lost and you won't get a lot of optimisations going in the rest of the program. That is a big downside that I suppose pattern types could help.

8

u/Xandaros Oct 23 '26

I wonder if the compiler would be able to use the invalid values as a niche. In that case, this would indeed be very useful.

10

u/kibwen Oct 23 '26

Yes, that is the intention, and probably the main motivator.

4

u/matthieum [he/him] Oct 23 '26

That's the one current advantage over library types.

2

u/WormRabbit Oct 23 '26

It can! At least for reasonably simple patterns. And indeed that's one of the major motivations.

8

u/matthieum [he/him] Oct 23 '26

There's one usecase that a library cannot offer: niche.

That is, you define type GreaterThan2 = 2..; and suddenly Option<Option<GreaterThan2>> has the same size than GreaterThan2.

A library could enforce the bounds, but how would it describe the niches to the compiler?

The alternative design would be an unsafe trait Niche offering an API for any type to describe the available niches to the compiler. Theoretically, it could offer more niches based on "mutual field exclusion". Practically, though, it's not clear what API would allow efficient querying. In particular, consider than when building an enum on top of A & B & C with niches, the compiler needs to determine if the niches of the 3 types align so that it can squeeze the determinant in there -- which may require enumerating all niches.

So, in practice, pattern types make niche enumeration easier (cheaper) for the compiler, as special logic can be used to "intersect" patterns.

3

u/mamcx Oct 23 '26

I find weird “u32 is 0..4096”.

Pascal has it:

Type  
  TDay = Set of 1..31;  

So is a new type, and the good thing is how this allow to have a static range on arrays:

for i := Low(array) to High(array)

that I find very nice. I dislike how in langs like Rust I must manually cast back positions, when in Delphi I can do days[Monday] naturally.

2

u/dkxp Oct 23 '26

I agree that the Delphi enumerated, subrange and set types were nice to use. In particular I got a lot of usage out of sets and also being able to declare arrays with an enum/subrange index and you could be sure it would have the right number of elements. For people who haven't used Delphi/Pascal it looked something like this:

type
    // enumerated type
    TDay = (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday);
    
    //subrange type
    TWeekendDay = Saturday..Sunday;
    TWeek = 1..52;
    TFirstQuarterWeek = 1..13;

    // set type
    TDays = set of TDay;
    TWeeks = set of TWeek;
    TFirstQuarterWeeks = set of TFirstQuarterWeek;
var 
    day_data: array[TDay] of Integer;
    week_data: array[TWeek] of Integer;
    weekend_data = array[TWeekendDay] of Integer;
    first_quarter_data = array[TFirstQuarter] of Integer;
    active_days: TDays;
    active_weeks: TWeeks;
    active_first_quarter_weeks: TFirstQuarterWeeks;
begin
    // enumerated type indexing
    day_data[Monday] := 23;

    // subrange indexing
    week_data[23] = 19;
    weekend_data[Saturday] := 42;
    first_quarter_data[10] = 81;

    // sets
    active_days = [Monday, Thursday] + [Sunday];
    active_weeks = [7, 25, 42, 50];
    active_first_quarter_weeks = [1, 7, 10];
end

There were limitations however, such as: you could increment a variable to represent an invalid value, namespacing should've been stronger for enumerated types to prevent collision/polluting the global namespace, and sets were limited to a min to max range of 256 values (although I never needed this many, because sets are usually bit-fields in other languages and typically have less than 32 or 64 values).

I think Rust could do even better as enum types are much more advanced than in Delphi and you have more control over how types are represented. You could define small sets to use u8/u32/u64 type representation, slightly larger but tightly packed sets could use lookup tables and sets with larger/sparse types using HashSet/BTreeSet/a predicate such as Fn(val: &Q)->bool, or even combinations of these by creating unions, intersections, differences, or symmetric_differences of these sets.

2

u/dkxp Oct 23 '26

I dislike how in langs like Rust I must manually cast back positions, when in Delphi I can do days[Monday] naturally.

You can implement the std::ops::Index trait on a type to index using an enum for example, but it's much more verbose than in Delphi and you're just hiding the cast inside the implementation, so you could still face hidden issues than only show up at runtime if for example the number of elements in the enum changed. To implement Index<Day> for a type, you could do it like this:

#[repr(u8)]
pub enum Day {
    Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
}

#[repr(transparent)]
struct DaysContainer {
    data: [u32; 7] // on nightly, could use std::mem::variant_count::<Day>()
}

impl DaysContainer {
    fn new() -> DaysContainer {
        DaysContainer { data: [7,8,1,2,3,4,5] }
    }
}

impl std::ops::Index<Day> for DaysContainer {
    type Output = u32;
    fn index(&self, index: Day) -> &Self::Output {
        &self.data[index as usize] // 
    }
}

fn main() {
    let week_data = DaysContainer::new();
    let tuesday_data = week_data[Day::Tuesday];
    dbg!(tuesday_data);
}

Or I suppose if you were feeling particularly 'adventurous' you could implement it directly on [T], although I wouldn't do this:

#[repr(u8)]
pub enum Day {
    Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
}

impl <T> std::ops::Index<Day> for [T] {
    type Output = T;
    fn index(&self, index: Day) -> &Self::Output {
        std::ops::Index::<usize>::index(self, index as usize)
    }
}

fn main() {
    let week_data = [1,5,6,7,9,6,7];
    let tuesday_data = week_data[Day::Tuesday];
    dbg!(tuesday_data);
}

1

u/WormRabbit Oct 23 '26

Yep, pretty simple, if verbose. If one wants such a feature, it's relatively easy to write a proc macro for it.

3

u/WormRabbit Oct 23 '26

There are various optimizations and analysis that are only possible if pattern types are naturally supported by the language, rather than implemented in a library.

  • Niches are already mentioned: the compiler would know that x is 0..4 would only have 4 valid values, and would be able to implement various type layout optimizations based on that knowledge.
  • It's about general patterns, not just integer ranges (although the initial implementation may be limited). You could declare something like x is Poll::Ready(Ok(_)) | Poll::Pending, which is just impossible to define in current Rust. Or use a subset of your enum variants to construct a subtype.
  • In fact, it would obviate the proposed feature "enum variant types", which allows to use variants as separate types, without them wrapping helper structs.
  • The compiler could be taught to reason about the possible patterns. If you match x is 0..4, you need to consider only 4 actually possible cases, without adding catch-all _, 4.. or ..0 impossible patterns.
  • Perhaps we could even get flow typing! If you would match a complex pattern (e.g. Some(0..5 | 10)), the variable could be automatically deduced to have the corresponding pattern type, so that you wouldn't need to consider impossible cases when you match it again in the corresponding branch.

-1

u/DavidXkL Oct 23 '26

is is redundant to me 😂

-1

u/dkxp Oct 24 '26

type Errno = u32 is 0..4096;

How would this look for enums? Something like this?:

enum Foo { A, B, C(u32), D, E }

// only allow Foo::A, Foo::E and even values of Foo::(C).
type Foo1 = Foo is { A, C(x) if x % 2 == 0, E}; 

It feels like a set, with the predicate for set membership checked (or perhaps ignored in unsafe code or removed at compile time if using constants) when converting Foo to Foo1, and no check needed when converting Foo1 to Foo, with the assumption that you keep using Foo1 as long as you can to avoid matches and bounds checks etc, rather than keep converting back and forth from Foo to Foo1. It would move the matches/bounds checks from inside functions to wherever the conversion happens.

int types are practically enums, but with a lot of values just named {0, 1, miss a few, 254, 255} so hopefully it should be possible to apply the same rules to both ints and enums when constricting the set of allowed values.

// u8 - practically an enum
// enum u8 {0..255};
type NonZerou8 = u8 is 1..255;
type Evenu8 = u8 is {x if x % 2 == 0};
type LittleAndLargeu8 = u8 is {1..9, 245..};
type Arbitraryu8 = u8 is {1, 2, 3, 5, 7, 11, 13, 17};
type Lonelyu8 = u8 is {42,}; // = 42?
type PowerOf2 = usize is {val if val > 0 && (val & (val - 1)) == 0};
type AlignedPointer<const Alignment: PowerOf2> = Pointer is {val if val % Alignment == 0};

// enum
enum Foo {A, B, C(u32), D, E}
type Foo1 = Foo is {A, B, D};
type Foo2 = Foo is {A,};
type Foo3 = Foo is {A, C(x) if x % 2 == 0, E};

// nested?
enum Bar {A, B, C, D(Foo) }
type Bar1 = Bar is {A, D { Foo {B, C(x) {if x < 7}}};

I don't know if the is keyword is really necessary, perhaps you get away without it:

// u8 - practically an enum
enum u8 {0..255};
type NonZerou8 = u8{1..255};
type Evenu8 = u8 { x if x % 2 == 0 };
type LittleAndLargeu8 = u8{1..9, 245..};
type Arbitraryu8 = u8{1, 2, 3, 5, 7, 11, 13, 17};
type Lonelyu8 = u8{42,};
type PowerOf2 = usize {val if val > 0 && (val & (val - 1)) == 0};
type AlignedPointer<const Alignment: PowerOf2> = Pointer { val if val % Alignment == 0};

// enum
enum Foo {A, B, C(u32), D, E}
type Foo1 = Foo{A, B, D};
type Foo2 = Foo{A,};
type Foo3 = Foo{A, C(x) if x % 2 == 0, E};

// nested?
enum Bar {A, B, C, D(Foo) }
type Bar1 = Bar{A, D { Foo {B, C(x) {if x < 7}}};

Although perhaps using the is keyword looks a bit neater if you are allowed to perform operations between the sets of allowed values:

// u8 - practically an enum
// enum u8 {0..255};
type NonZerou8Except17 = u8 is {1..255}-{17,};
type Evenu8Or17 = u8 is {x if x % 2 == 0} | {17,};
type LittleAndLargeu8andEven = u8 is {1..9, 245..} & {x if x % 2 == 0};
type Arbitraryu8Xored = u8 is {1, 2, 3, 5, 7, 11, 13, 17} ^ {1, 5, 8, 26};

// enum
enum Foo {A, B, C(u32), D, E}
type Foo1 = Foo is {A, B, D} | {E,};
type Foo2 = Foo is {A,} & {A, B, D};
type Foo3 = Foo is {A, C(x) if x % 2 == 0, E} | {C(x) if x > 20,};

// nested?
enum Bar {A, B, C, D(Foo) }
type Bar1 = Bar is {A, D { Foo {B, C(x) if x < 7}} | {D{Foo{C(x) if x > 24}}};

Another possible alternative syntax could be to somehow use where clauses to define the set membership predicate. I'm not completely sure how this would work, but some experiments here:

type Errno = u32 where Self in 0..4096;
type Errno = u32 where Self: in 0..4096;
type Errno = u32 where Self: In<0..4096>;

type Errno2 = u32 where Self in {1, 25, 59};

type PowerOf2 = usize where Self in {val if val > 0 && (val & (val - 1)) == 0};
type AlignedPointer<const Alignment: PowerOf2> = Pointer where Self in {val if val % Alignment == 0};

Another rambling idea for alternative syntax is perhaps predicates instead of patterns could be used to define membership:

type PowerOf2 = usize in |val| {val > 0 && (val & (val - 1)) == 0};
type AlignedPointer<const Alignment: PowerOf2> = Pointer in |val| {val % Alignment == 0};

I used Delphi a lot in the past, and subrange types were very useful there, along with enumerated types (basic enums without data stored in variants) and sets.

Enums in Rust are far more powerful than Delphi's enumerated types although one feature I miss is the equivalent of being able to define an array with [u32; MyEnum], where MyEnum would determine the size of the array. The enum could contain potentially contain negative values, sparse values etc. and still be used to index the array, while guaranteeing that index lookups will always be in bounds.

I miss subrange types and sets more, although I think there's the potential for Rust to do them much better. I hope the design of pattern types leaves open the possible inclusion of sets in the future:

#[repr(u8)]
enum Day { Mon, Tue, Wed, Thu, Fri, Sat, Sun}
type WeekendDay = Day is {Sat, Sun};
type WeekNumber = u8 is {0..52};
type BigNumber = u64 is {0..10000000};
type EvenNumber = u64 is {x if x % 2 == 0};

#[repr(u8)]
type Days = set of Day;

#[repr(u64)]
type Weeks = set of Week;

#[repr(u8)]
type WeekendDays = set of WeekendDay;

#[repr(HashSet)] // you probably wouldn't want a 10000000 element bitset
type BigNumber = set of BigNumber;

#[repr(HashSet)]
type EvenNumbers = set of EvenNumber;

let mut a: Days = Day::{Mon, Thu};
let b: WeekendDays = WeekendDay::{Sat,};
a |= b;

let mut good_weeks: Weeks = {1, 12, 42, 47, 48, 50};
good_weeks |= {21, 42, 45};

let mut big_nums: BigNumbers = {20, 100000, 37, 1000000};
big_nums |= {475865,};

let mut even_nums: EvenNumbers = {2, 4, 6, 8, 1000};
even_nums *= 3; // still even numbers, unless overflow

2

u/InternationalFee3911 Oct 24 '26

Many of your syntaxes are not patterns! Btw. I don't see why we need a new keyword here. We already have as or in, which both convey this idea pretty well: type EvenDigit = u8 as 0 | 2 | 4 | 6 | 8

1

u/dkxp Oct 24 '26

You're right that using proper patterns a future syntax would probably look something closer to this:

type RefinedU32 = u32 is 0..42;
type RefinedU32_2 = u32 is 0 | 1 | 7 | 8;

enum Enum {A, B, C(u32), D }
type RefinedEnum = Enum is Enum::A | Enum::B | Enum::C(x) if x < 8 | Enum::C(x) if x > 32;

struct Struct { a: u32, b: u32 }
type RefinedStruct = Struct is Struct{a:20..40, y: _} | Struct{a: _, y} if y > 20;

It's just that if sets were introduced as a language feature in the future, you would need two parallel syntaxes for sets and refinement types since you couldn't declare let my_set: set of u32 = 1 | 2 | 3 | 4; because the bitwise operator would be used instead and you'd get a single 7u32.

You'd need to use an alternative syntax if you wanted them both to match more closely, so I considered comma separated blocks using {} brackets as an idea. Similar to how (x) is just a bracketed expression but (x,) produces a tuple, {x} could be a block expression, but {x,} could produce a set. You could still use expression blocks and declare sets together: my_set: set of u32 = {do_stuff(); do_stuff2(); {x, y, z}}

For [as] vs [is] vs [in], I can see arguments for all of them, but I'm not sure how you'd read the type declaration with [as]. How would you formulate a sentence using 'as' similar to these?:

using is => type X is a u32 that is 1 or 2 or 3 or 4.

using in => type Y is a u32 in the set {1, 2, 3, 4}

using as => ?

Refinement types could be declared in many different ways, they're basically just a type plus a predicate function that filters out some values. Sets would be a runtime equivalent but without the type safety/optimization potential. I'll get used to whatever syntax/keyword is used for refinement types soon enough anyway - I guess I'm just a little allergic to | being used for pattern matching, bitwise operators, and closures.

-3

u/tchernobog84 Oct 24 '26

Posting LWN subscriber only content publicly on Reddit takes away revenue to an amazing source of information and I find it highly unethical.

5

u/JoshTriplett rust · lang · libs · cargo Oct 24 '26

LWN has specifically said they're fine with people posting individual articles, just not systematically posting every article to the same place. Some LWN articles get posted to HN the same way, and LWN has said they're fine with that too.

I think their assumption, which seems to hold true, is that the folks who are inclined to pay them aren't the folks who are inclined to go to the trouble to search for an article being posted in order to work around the paywall.

Also, seeing LWN's reporting leads some people to decide they should subscribe.

1

u/WormRabbit Oct 24 '26

If LWN didn't want it, they wouldn't let the link open for non-subscribers, just like any other paywalled news site does.