castingrust

Am I casting integer types too much?


I'm very new to Rust and I've been re-solving Project Euler questions. The thing is, I realised that I kept casting integer types (mainly i32-i64) around to fit my statement; for iterators, in loops, for function inputs, for conditionals etc. Is it normal?

I'm guessing I'm doing something wrong working with one-off functions going through PE and coming from mainly dynamically typed languages.

I always try to use the smallest possible (or most feasible) integral type for the problem and I feel like I should just go with i64 for everything and be done with it instead of so much casting around.

Which is a better/recommended approach, blanket i64 type or sensible integer types with casting in code?

edit: After the comments I wanted to clarify, this is not exactly a code-review query but about best practices and readability concerns as in which of the two choices are preferred. I reckon the performance impact of casting is negligible when not misused in loops.

Unrelated PS: I was doing P4 with a twist of prime factors, turns out there are no palindromes that are a product of two 4-digit primes and the largest one from two 3-digit primes is 99899


Solution

  • I always try to use the smallest possible (or most feasible) int type for the problem

    Here you are. Optimization. (Because why else would you do that?)

    Rust encourages you to think about the integer types. This leads to a better defined and explicit program behaviour, helps catch a certain type of bugs and lets you optimize.

    But coming from a language that wasn't that meticulous you'd likely to overdo it. That's how our mind often works: when we encounter some new ability or skill we try to use it everywhere.
    (cf. "новообразования развития" in Выготский)

    This is often a problem with Rust. The language would introduce programmers to certain new concepts (safe borrowing, zero-cost futures) and then as people we'd rush and jumble the things we had little experience with, borrowing ourselves into a corner or using the futures absolutely everywhere.

    You're trying to optimize your program, using the smallest possible integer type, even though you feel it makes your life less comfortable. If you're asking this question on stackoverflow then I'd go out on a limb and say, yes, you're casting too much!

    You probably know the Knuth's motto, that "premature optimization is the root of all evil".

    Don't let over-optimizing ruin your programming experience. Optimize only when you're comfortable with it. When you want to!

    If you're afraid of premature pessimization then save this fear for the algorithms. Remember that programming in most dynamic languages you don't have that much freedom to over-optimize and yet your dynamic language programs still work.