作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个基于usize
输入返回compound duration的函数:
pub fn format_dhms(seconds: usize) -> String
6000000
:
println!("{}", format_dhms(6000000));
69d10h40m
as usize
。例如,如果我使用
Duration
或
as_secs() = u64
方法使用
as_nanos() = u128
的输出。
u128::MAX
时,我想像
usize
一样通过将输入截断为最大接受值来处理它。
#![allow(unused)]
use std::time::Instant;
fn format<T: Into<usize>>(number: T) {
if number == 0 {
//println!("{}", number)
} else {
//println!("{}> 0", number)
}
}
fn main() {
let now = Instant::now();
format(now.elapsed().as_nanos()); // u128
format(now.elapsed().as_secs()); // u64
}
error[E0277]: the trait bound `usize: std::convert::From<i32>` is not satisfied
the trait `std::convert::From<i32>` is not implemented for `usize`
...
error[E0369]: binary operation `==` cannot be applied to type `T`
<T: Into<size>>
可以使用,但是我需要使用
as usize
。
format(now.elapsed().as_nanos() as usize);
as usize
,或者当输入只是没有定义类型的数字时如何实现相同的行为?
最佳答案
您可以使用std::mem::size_of
来检查输入类型是否适合usize
,并在不适合时使用位操作来截断:
use std::convert::{ TryFrom, TryInto };
use std::fmt::Debug;
use std::ops::BitAnd;
use std::time::Instant;
fn format<T: TryInto<usize> + TryFrom<usize> + BitAnd<Output=T>> (number: T)
where <T as TryFrom<usize>>::Error: Debug,
<T as TryInto<usize>>::Error: Debug
{
let number: usize = if std::mem::size_of::<T>() <= std::mem::size_of::<usize>() {
number.try_into().unwrap()
} else {
(number & usize::MAX.try_into().unwrap()).try_into().unwrap()
};
if number == 0 {
//println!("{}", number)
} else {
//println!("{}> 0", number)
}
}
unwrap
绝不会失败。
关于rust - 如何实现Into trait而不使用 `as usize`将所有输入转换为usize?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61898602/
我是一名优秀的程序员,十分优秀!