Antonin GAVREL
Antonin GAVREL

Reputation: 11219

Rust: Implicitly convert from usize to the corresponding int type

I wonder if anyone has a solution to allow implicit conversion from usize type (that we obtain from accessing array index, or getting vector length) to i32 ? Is it even possible?

Of course I assume that vector length and array bounds are within i32 limits.

Upvotes: 3

Views: 5029

Answers (2)

loops
loops

Reputation: 5635

You can use the TryInto trait in function arguments to do implicit conversions from the perspective of callers. It still involves conversion, but it moves the complexity to the function being called:

use std::convert::TryInto;

fn stuff(val: impl TryInto<i32>) {
    // use try_into trait method
    let val = match val.try_into() {
        Ok(v) => v,
        Err(_) => panic!("couldn't fit in i32"),
    };
    println!("in stuff: val has {} leading zeros", val.leading_zeros());
}

fn main() {
    let letters = ['a', 'b', 'c'];
    let len = letters.len();
    println!("in main: len has {} leading zeros", len.leading_zeros());
    stuff(len); // implict conversion
}

outputs

in main: len has 62 leading zeros
in stuff: val has 30 leading zeros

Try on the playground

Upvotes: 2

mikebarber
mikebarber

Reputation: 21

I don't think there is a way to do it implicitly. If there is, it wouldn't be very idiomatic: Rust decided to avoid implicit conversions and ensure that all conversions are done explicitly.

For straightforward conversions, as is probably the best bet. For conversions where you're concerned about overflow, etc. you've got From and TryFrom. For small lengths converting to i32, length as i32 is probably the easiest.

It does make stuff a bit more verbose, but I find it's a fairly good compromise.

There's a good writeup in the Rust book on as here: https://doc.rust-lang.org/rust-by-example/types/cast.html#casting

Upvotes: 2

Related Questions