如何在 u32 和 usize 之间进行惯用转换? [英] How to idiomatically convert between u32 and usize?
问题描述
此代码有效并打印b":
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
由于某些外部原因,我必须对变量 n
使用 u32
类型.如何将 u32
转换为 usize
并在 nth()
中使用它?
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()
?
推荐答案
as
运算符适用于所有数字类型:
The as
operator works for all number types:
let ch = s.chars().nth(n as usize).unwrap();
Rust 强制您强制转换整数以确保您知道有符号或溢出.
Rust forces you to cast integers to make sure you're aware of signedness or overflows.
整数常量可以有类型后缀:
Integer constants can have a type suffix:
let n = 1u32;
但是要注意负常数,比如-1i32
在内部是-
1i32
.
However, note that negative constants, such as -1i32
is internally -
1i32
.
没有明确类型规范声明的整数变量显示为 {integer}
并且将从方法调用之一正确推断.
Integer variables declared without an explicit type specification are shown as {integer}
and will be properly inferred from one of the method calls.
这篇关于如何在 u32 和 usize 之间进行惯用转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!