小程序毕业设计-基于springboot+小程序的个人健康管理系统小程序(源码+LW+部署文档+全bao+远程调试+代码讲解等)
2026/6/6 9:17:06
这是一个 Rust 时间库中的Duration结构体实现,提供高精度的时间跨度表示。
std::time::Duration不同,支持负时间间隔RangedI32确保纳秒值在有效范围(-999,999,999 到 999,999,999)pubstructDuration{seconds:i64,// 整秒数nanoseconds:Nanoseconds,// 纳秒部分(带范围检查)padding:Padding,// 用于编译器优化(niche value optimization)}提供了常用时间单位的预定义常量:
// 基本单位pubconstNANOSECOND:Self=Self::nanoseconds(1);pubconstMICROSECOND:Self=Self::microseconds(1);pubconstMILLISECOND:Self=Self::milliseconds(1);pubconstSECOND:Self=Self::seconds(1);pubconstMINUTE:Self=Self::minutes(1);pubconstHOUR:Self=Self::hours(1);pubconstDAY:Self=Self::days(1);pubconstWEEK:Self=Self::weeks(1);// 特殊值pubconstZERO:Self=Self::seconds(0);pubconstMIN:Self=Self::new_ranged(i64::MIN,Nanoseconds::MIN);pubconstMAX:Self=Self::new_ranged(i64::MAX,Nanoseconds::MAX);多种构造方式:
// 从秒和纳秒创建letd1=Duration::new(1,500_000_000);// 1.5秒// 从时间单位创建letd2=Duration::hours(2);// 2小时letd3=Duration::minutes(30);// 30分钟// 从浮点数创建letd4=Duration::seconds_f64(1.5);// 1.5秒letd5=Duration::seconds_f32(0.5);// 0.5秒// 从小单位创建letd6=Duration::milliseconds(1500);// 1500毫秒letd7=Duration::microseconds(500);// 500微秒letd8=Duration::nanoseconds(100);// 100纳秒letduration=Duration::hours(2)+Duration::minutes(30);duration.whole_hours();// 2duration.whole_minutes();// 150duration.whole_seconds();// 9000duration.whole_days();// 0letduration=Duration::seconds(1)+Duration::milliseconds(500);duration.as_seconds_f64();// 1.5duration.as_seconds_f32();// 1.5duration.subsec_milliseconds();// 500duration.subsec_microseconds();// 500000duration.subsec_nanoseconds();// 500000000letpos=Duration::seconds(5);letneg=Duration::seconds(-5);letzero=Duration::ZERO;pos.is_positive();// truepos.is_negative();// falsepos.is_zero();// falseneg.is_positive();// falseneg.is_negative();// trueneg.is_zero();// falsezero.is_zero();// trueletd1=Duration::seconds(5);letd2=Duration::seconds(3);// 普通加法(可能panic)letsum=d1+d2;// 8秒// 检查溢出的加法letchecked=d1.checked_add(d2);// Some(8秒)// 饱和加法letsaturated=Duration::MAX.saturating_add(d2);// Duration::MAXletd1=Duration::seconds(5);letd2=Duration::seconds(3);letdiff=d1-d2;// 2秒letneg_diff=d2-d1;// -2秒letchecked=d1.checked_sub(d2);// Some(2秒)letd=Duration::seconds(10);letmultiplied=d*2;// 20秒letdivided=d/2;// 5秒letfloat_mul=d*1.5;// 15秒letfloat_div=d/2.5;// 4秒letd=Duration::seconds(5);letnegated=-d;// -5秒usestd::time::DurationasStdDuration;// 从标准库转换letstd_duration=StdDuration::from_secs(5);lettime_duration=Duration::try_from(std_duration).unwrap();// 转换为标准库(无符号)letunsigned=time_duration.unsigned_abs();// 与标准库比较assert_eq!(Duration::seconds(5),StdDuration::from_secs(5));assert!(Duration::seconds(10)>StdDuration::from_secs(5));letduration=Duration::hours(2)+Duration::minutes(30);// 完整格式println!("{}",duration);// "2h30m0s"// 简洁格式(带精度)println!("{:.2}",duration);// "2.50h"println!("{:.0}",duration);// "3h"RangedI32保证纳秒值始终有效Padding字段优化内存布局#[inline]这个实现特别适合需要处理相对时间、倒计时、时间差计算的场景,弥补了标准库Duration不支持负值的不足。