2个版本
使用旧的Rust 2015
0.1.1 | 2017年12月13日 |
---|---|
0.1.0 | 2017年12月13日 |
#96 在 #following
每月26次 下载
7KB
116 行
Rust RangeType
受Ada启发的Rust Range类型。
文档
在这里.
特性
编译时检查
以下将无法编译
#[macro_use]
extern crate rangetype;
fn main() {
// Range with a value of 5 that should be within in range [-5, 2]
let x = range!(5, -5..2);
}
运行时检查
// Will panic since the two numbers are for different ranges
let x = range!(5, 0..10);
let y = range!(10, 10..128);
let z = x + y; // panic!
// Will panic because 5 + 10 = 15 which will overflow the range of 0..10
let x = range!(5, 0..10);
let y = range!(10, 0..10);
let z = x + y; // panic!
lib.rs
:
此crate提供了一种数值类型,在所有数学运算中自动执行范围检查。如果违反范围,代码将立即崩溃。
使用range!
宏时,您将自动获得编译时范围检查。您需要导入static_assertions
crate才能使用range!
。
您还可以导入RangeType
,尽管使用宏是推荐的。
示例
#[macro_use]
extern crate rangetype;
#[macro_use]
extern crate static_assertions;
use rangetype::RangeType;
fn main() {
// A value of 5 that must be between 0 and 128
let x = range!(32, 0..127);
// You can also use floating-point types (and the constructor)
let y = RangeType::new(4.5, 0.1..99.9);
let z = range!(64, 0..127);
// x + z = 96
println!("{}", x + z);
// println!("{}", z + z); // This would panic
// Ranges can be adjusted
let a = x.with_range(0..255);
// And the raw value can be retrieved like so
let b = x.as_raw();
}
Mul
、Div
、Add
、Sub
和Neg
特性在RangeType
结构体上实现。
依赖项
~46KB