文档说的usize是
指针大小的无符号整数的操作和常量.
在大多数情况下,我可以替换usize,u32没有任何反应.所以我不明白为什么我们需要两种类似的类型.
例如,此代码工作并打印"b":
fn main() {
let s = "abc";
let ch = s.chars().nth(1).unwrap();
println!("{}", ch);
}
Run Code Online (Sandbox Code Playgroud)
另一方面,此代码导致不匹配类型错误.
fn main() {
let s = "abc";
let n: u32 = 1;
let ch = s.chars().nth(n).unwrap();
println!("{}", ch);
}
Run Code Online (Sandbox Code Playgroud)
error[E0308]: mismatched types
--> src/main.rs:5:28
|
5 | let ch = s.chars().nth(n).unwrap();
| ^ expected usize, found u32
Run Code Online (Sandbox Code Playgroud)
出于某种原因,我必须使用u32变量类型n.我怎么能转换u32到usize并在使用它nth()?
使用'as'编译的第一次转换,但使用'From'特性的第二次转换不会:
fn main() {
let a: u64 = 5;
let b = a as usize;
let b = usize::from(a);
}
Run Code Online (Sandbox Code Playgroud)
使用Rust 1.22.1我收到以下错误:
error[E0277]: the trait bound `usize: std::convert::From<u64>` is not satisfied
--> src/main.rs:4:13
|
4 | let b = usize::from(a);
| ^^^^^^^^^^^ the trait `std::convert::From<u64>` is not implemented for `usize`
|
= help: the following implementations were found:
<usize as std::convert::From<bool>>
<usize as std::convert::From<std::num::NonZeroUsize>>
<usize as std::convert::From<u16>>
<usize as std::convert::From<u8>>
= note: required by `std::convert::From::from`
Run Code Online (Sandbox Code Playgroud)
当我更换u64时u8,没有更多的错误.从错误消息中,我了解该 …
我想将一个usize类型变量转换为u32Rust中的类型变量.我知道usize变量可能包含一个大于2 ^ 32的值,在这种情况下转换应该失败.我正在尝试使用TryFrom特征来执行转换.
这是一个简单的例子(Nightly Rust,Playground):
#![feature(try_from)]
use std::convert::TryFrom;
fn main() {
let a: usize = 0x100;
let res = u32::try_from(a);
println!("res = {:?}", res);
}
Run Code Online (Sandbox Code Playgroud)
代码无法编译,出现以下编译错误:
error[E0277]: the trait bound `u32: std::convert::From<usize>` is not satisfied
--> src/main.rs:6:15
|
6 | let res = u32::try_from(a);
| ^^^^^^^^^^^^^ the trait `std::convert::From<usize>` is not implemented for `u32`
|
= help: the following implementations were found:
<u32 as std::convert::From<std::net::Ipv4Addr>>
<u32 as std::convert::From<u8>>
<u32 as …Run Code Online (Sandbox Code Playgroud)