【发布时间】:2019-02-14 20:13:35
【问题描述】:
我正在尝试编写一个通用函数来计算任何有符号整数类型的绝对值。当值是可能的最低负值时,它应该返回错误,例如 8 位 abs(-128) 无法表示。
我得到这个为i8工作:
pub fn abs(x: i8) -> Result<i8, String> {
match x {
x if x == -128i8 => Err("Overflow".to_string()),
// I know could just use x.abs() now but this illustrates a problem in the generic version below...
x if x < 0i8 => Ok(-x),
_ => Ok(x),
}
}
fn main() {
println!("{:?}", abs(-127i8));
println!("{:?}", abs(-128i8));
}
我无法使用通用版本。具体来说我有两个问题:
- 我一般如何确定最小值? C++
std::numeric_limits<T>::min()的 Rust 等价物是什么?有例如std::i32::MIN但我不会写std::T::MIN。 - 我在匹配臂上的通用实现错误,带有“无法通过移动绑定到模式保护中”的负值(但非通用版本没有。)
use num::{traits::Zero, Integer, Signed}; // 0.2.0
pub fn abs<T>(x: T) -> Result<T, String>
where
T: Signed + Integer + Zero,
{
match x {
//x if x == ***rust equivalent of std::numeric_limits<T>::min()** => Err("Overflow".to_string()),
x if x < T::zero() => Ok(-x),
_ => Ok(x),
}
}
fn main() {
println!("{:?}", abs(-127i8));
println!("{:?}", abs(-128i8));
}
error[E0008]: cannot bind by-move into a pattern guard
--> src/main.rs:9:9
|
9 | x if x < T::zero() => Ok(-x),
| ^ moves value into pattern guard
【问题讨论】: