为什么Rust将usize转换为u128失败? [英] Why is Rust's usize to u128 conversion considered failable?

查看:71
本文介绍了为什么Rust将usize转换为u128失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看看:

use std::convert::{From, TryFrom};

fn main() {
  let size: usize = 42;
  let good: u128  = u128::try_from(size).unwrap(); // works fine
  let bad:  u128  = u128::from(size);              // doesn't compile!
}

据我所知, usize 是整数类型,并且永远不会大于128位.因此,我看不到 usize->u128 转换可能会失败.那么,为什么 u128 不实现 From< usize> ?

As far as I know, usize is an integral type and those are never larger than 128 bits. Therefore, I see no way the usize -> u128 conversion can fail. So, why doesn't u128 implement From<usize>?

更新:Rust的文档说:

从T表示U意味着到T表示U

From T for U implies Into U for T

尽管 usize->u128 看起来不错, u128->usize 不会.好的,但是为什么没有为 useize 实施 Into< u128> ?

Though usize -> u128 seems fine, u128 -> usize doesn't. OK, but why isn't Into<u128> implemented for usize instead?

推荐答案

尽管使用->u128看起来不错,u128->使用不.好的,但是为什么没有为Usize实施Into呢?

Though usize -> u128 seems fine, u128 -> usize doesn't. OK, but why isn't Into implemented for usize instead?

因为就Rust而言,尽管保证usize始终至少为16位,但不能保证最高始终为 64位.

Because while usize is guaranteed to always ever be at least 16 bits as far as Rust is concerned, it's not guaranteed to always ever be at most 64 bits.

似乎不太可能有用,但从技术上讲,没有什么可以排除256位指针,并且由于保证usize是指针大小,因此可以使 usize->成为可能.u128 转换失败.

It seems unlikely to ever be useful but technically nothing precludes 256 bits pointers, and since usize is guaranteed to be pointer-sized it would make the usize -> u128 conversion failible.

这篇关于为什么Rust将usize转换为u128失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆