0

How can I convert a usize to u32?

For example I want to store the length of a Vector (usize) to a variable u32 I tried i32::from(v) // or v.into(). where v is the length of the vector but errored

I tried v as u32 and it compiles fine but I am interested in finding the correct way of doing this as this https://stackoverflow.com/questions/28273169/how-do-i-convert-between-numeric-types-safely-and-idiomatically suggests that generally speaking using as instead of from should be avoided

However trying to use from in ink! errors I am guessing because of no std access

Also looking at similar posts like How to convert Vec<u8> to u32 in Substrate runtime? I can see that core::str::from_utf8 was used for a different conversion

So my questions are:

Q1: how to convert usize to u32

Q2: where to read more about conversions between types in ink! e.g. read about examples similar to core:: above

2 Answers 2

3

Basically, using binary as operator to convert from one type to another is common way. In case of usize, if usize value is greater than max value of u32, then it will cause panic at runtime. To handle this safely, Rust also offers traits that facilitate type conversions upon implementation like this in the under convert model of rust std.

practice reference

1
  • 1
    Many thanks. This has been very helpful
    – Sokrates
    Commented Feb 4, 2023 at 7:04
2

I want to point out that:

as won't cause a panic. It just loses some precision. https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=1cf0b2dc9955ef9d6a54c7c95998f331


You should never not do this, and you need to write some logic to handle this. Something like:

if usize_v as u128 > u32_v as u128 { ... } else { ... }

But if your logic doesn't care about the precision losses. Or you know the usize value is always smaller than the u32::MAX. Just use as.

1
  • I really appreciate the valuable comments and add-ons
    – Sokrates
    Commented Feb 4, 2023 at 15:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.