To Nat or not to Nat (vs Nat8/16/32/64)

Over my time developing with Motoko I haven’t landed on a general practice on when to use Nat and when not to.
Generally I tend to default to Nat/Int vs Nat8/16/32/64 unless I have a specific need, but I run into a few different issues:

  • Hashing: Nat hashing doesn’t really have a default and I dont feel great about any of my implementations. A lot of the time I just convert it to a Nat32 because my numbers are rarely large, but it seems like a bad practice
  • JS Client BigInt: Whenever I use Nat for api calls, its super annoying to deal with BigInt in JS, even though 99% of the time it could fit in number
  • Something else that I cant seem to remember

But Im stuck, because I could just use Nat32 everywhere by default, which would solve a lot of problems, but Nat seems to be the default things for like indexing and library usage

Im just curious on other developers best practices or any thoughts on the subject

4 Likes

One point I’d like to add is some neuron Id’s don’t fit into JS Number(). It’s worth keeping that in mind as BigInt would always be safe bet here.

Well how about using Nat ↔ Text? Where Text would support hashing as well.
I never calculated how much optimal would that be memory wise. But conversion between is not very much.
I would love to know if this Nat-Text is bad, will stop using it.

We do need to solve the lack of hashing libraries in Motoko. I remember @rossberg himself saying that the memory allocation behind the scenes for Nat was highly optimised and the potential savings using bounded Nat types was not signifiant in most cases.

Expect for situations when binary manipulations are necessary I recommend to stick to Nat.

Edit: Found the original post (What is the maximum value of Nat64, Nat32, Nat16, Nat8, Int64, Int32, Int16, and Int8?)

1 Like