impl Solution {
pub fn find_max_average(nums: Vec<i32>, k: i32) -> f64 {
let mut curr:i32=0;
let mut ans:f64;
for i in 0..k {
curr += nums[i as usize];
}
ans=curr as f64/k as f64;
for i in k..nums.len() as i32 {
curr += nums[i as usize] - nums[(i-k) as usize];
ans = ans.max(curr as f64/k as f64);
}
return ans
}
}
This code works, it's for a leetcode problem (calculate max average of a subarray). However, being a beginner in rust, it took me quite a while to get this to compile - specifically, a lot of type casts were needed. The fn
signature was given.
Can this be improved? Does rust suggests the tradeoff of less readability (in my opinion, the above is not so readable) of the the code against failproof type safety? Or is this only subjective, and as the code gets improved, the supposed tradeoff goes away?
I second @cadolphs recommendation to cast your types at the beginning of the function to avoid needing to cast later, although would recommend to use .into()
(or .try_into()
as applicable) instead of as
like so:
let n: usize = k.try_into().unwrap();
The reasoning is that the behavior of as
casting often isn't the desired behavior in the corner cases.
For example, let n = k as usize
would give a bad result if k
(an i32
) happens to be negative, it would sign-extend the value and then interpret it as positive, resulting in a huge n
. In contrast, .try_into()
would check to make sure k
could be properly converted to a usize
, returning an Err
if it could not be converted.
In general, by default you probably want to use .into()
(or .try_into()
) for casting, unless you fully understand the behavior of as
casting (and you actually desire that behavior).