This code works and prints "b":
fn main() {
let s = "abc";
let ch = s.chars().nth(1).unwrap();
println!("{}", ch);
}
On the other hand, this code results in a mismatch type error.
fn main() {
let s = "abc";
let n: u32 = 1;
let ch = s.chars().nth(n).unwrap();
println!("{}", ch);
}
error[E0308]: mismatched types
--> src/main.rs:5:28
|
5 | let ch = s.chars().nth(n).unwrap();
| ^ expected usize, found u32
For some external reason, I have to use the u32
type for variable n
. How can I convert u32
to usize
and use it in nth()
?
The
as
operator works for all number types:Rust forces you to cast integers to make sure you're aware of signedness or overflows.
Integer constants can have a type suffix:
However, note that negative constants, such as
-1i32
is internally-
1i32
.Integer variables declared without an explicit type specification are shown as
{integer}
and will be properly inferred from one of the method calls.We now have a pretty different answer when we try to compile your code, replacing the number
1
with a variable of typei32
:It means that now the compiler recommends you to use
n.try_into().unwrap()
that makes use of the traitTryInto
which in turn relies onTryFrom
and returns aResult<T, T::Error>
. That's why we need to extract the result with a.unwrap()
TryInto
documentationThe most cautious thing you can do is to use
TryFrom
and panic when the value cannot fit within ausize
:By blindly using
as
, your code will fail in mysterious ways when run on a platform whereusize
is smaller than 32-bits. For example, some microcontrollers use 16-bit integers as the native size: