r/Zig • • Oct 02 '22

Idea: generic integer

If you can do this:

var s = "hello";

Why can't you do this?

var i = 5;

Proposal: make this a "generic_int" with the following sematics:

This type of integer is guaranteed to either behave identically to a comptime_int or panic on overflow. Its size is undefined and unknowable at compilation time, but implementation is guaranteed to be >= isize. Saturating and wraparound operators are not applicable.

It's essentially a "runtime comptime_int".

It should be particularly useful for counters and indices in loops. Sure, you can just use isize for a generic ints, but I think this can make code cleaner.

0 Upvotes

5 comments sorted by

4

u/earthboundkid Oct 02 '22

In Go, constant numbers such as literals are untyped and all variables have to be typed. Zig could probably do something similar but more logically consistent. https://go.dev/blog/constants

4

u/XNormal Oct 02 '22

In zig, integer literals are comptime_int, an arbitrary size integer

2

u/[deleted] Oct 02 '22

Why not just use isize and not use wraparound arithmetic operations ? The + operator can panic on overflow

1

u/XNormal Oct 02 '22

What I am suggesting is close to making it implicitly isize.

  • with some adjustment to make it effectively indistinguishable from comptime_int

1

u/[deleted] Oct 13 '22

I'd rather have C-styled literals instead, e.g. 5isize or 5u5.