Pre-RFC: `?` operator in constants

Well, as I said, it'd need a FromIntegerLiteral trait as well, I was just thinking that the function on that trait would need to be passed something.

And having a compile-time-only big integer would be really useful for const generics stuff that wants a value without needing to pick a particular type for that value.

1 Like

this seems like basically zig's comptime_int

fwiw I tried experimentally implementing a FromIntegerLiteral trait in the past…it's more complicated that I'd like to admit. It's certainly possible, though.

why specifically integer literals, and not numeric literals in general? this seems like it could be useful for fixed point and bigfloats.

My original intent was nonzero literals, which became a bit more generalized. No particular reason not numeric literals.

1 Like

I said integer literals specifically because I'd expect different types (& traits) for integer and float literals, the same way that let x: f32 = 3; doesn't work and let y: i32 = 3.0; doesn't work.

They're already different categories in the literal inference, so I'd expect that to be preserved.

Honestly fwiw I find re-using the ? syntax to mean a different thing inside const blocks (even if it is implemented using the same try_v2 mechanism) to be confusing at best. I personally would expect for example const { bar()? } with const fn bar() -> Result<!,&'static str> { Err("Hi there!") } to evaluate to Err("Hi there!") and not to error at compile time.

One alternative I just thought about is if we allow "block nesting" (idk if such a proposal was made before), i.e. for example const try {} being equivalent to const { try { } } we could add a fail { }/ unwrap {} / panic {} (or however you wish to name it) block and have both const try {} and const unwrap {} blocks as a consequence of that and only allow those explicit variants instead of defaulting to one behaviour, or maybe add a default to a certain behaviour after doing a lot of user surveys/etc.

3 Likes

One of the nice things about it erroring at compile time is you get reasonably immediate feedback about this misconception. Portions of this discussion strike me as people just wanting novel things to be more verbose. My expectation is after getting used to ? being available in some kind of const/const try block no extra noise would be desired.

5 Likes

How so? ? involves a return, so it should resolve (as an expression) to divergence and cause control flow to exit from whatever fn contains the const {} block. At that point, it is not a const value, so the const block seems rather unused to me.

1 Like