【发布时间】:2017-09-28 00:31:14
【问题描述】:
此代码有效并打印“b”:
fn main() {
let s = "abc";
let ch = s.chars().nth(1).unwrap();
println!("{}", ch);
}
另一方面,此代码会导致类型不匹配错误。
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
由于某些外部原因,我必须将 u32 类型用于变量 n。如何将u32 转换为usize 并在nth() 中使用?
【问题讨论】:
-
将
usize转换为u32或反之亦然有哪些常见用例?
标签: types rust type-conversion