相关疑难解决方法(0)

`usize`和`u32`有什么区别?

文档说的usize

指针大小的无符号整数的操作和常量.

在大多数情况下,我可以替换usize,u32没有任何反应.所以我不明白为什么我们需要两种类似的类型.

rust

50
推荐指数
2
解决办法
1万
查看次数

如何在u32和usize之间进行惯用转换?

例如,此代码工作并打印"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.我怎么能转换u32usize并在使用它nth()

types type-conversion rust

14
推荐指数
2
解决办法
9992
查看次数

为什么允许使用`as`而不是`From`从u64到usize的类型转换?

使用'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)

当我更换u64u8,没有更多的错误.从错误消息中,我了解该 …

numbers type-conversion rust

13
推荐指数
2
解决办法
4406
查看次数

如何使用TryFrom将usize转换为u32?

我想将一个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)

rust

6
推荐指数
1
解决办法
2016
查看次数

标签 统计

rust ×4

type-conversion ×2

numbers ×1

types ×1