单元测试是用 #[test] 属性标记的简单函数,通常使用 assert! 或 assert_eq! 宏来检查结果。该函数仅测试时运行,运行方式是程序目录下,在命令行中敲入:cargo test。角度类补充单元测试如下
/*
* 角度弧度的类rad
** 编制人: $ource
* 修改版次及创建时间:0版完成版(2024年8月14日)
* 修改内容及时间:无
* 待完善问题:未定义梯度(grad)属性,未检查及调整rad到(-π,π)或(0,2π)范围。暂时不需要这些属性.
*/
const PI:f64=std::f64::consts::PI;
use std::ops::{Add, Sub, Mul, Div};
pub const ANGLE0:Angle=Angle{rad:0f64};
pub const ANGLE45:Angle=Angle{rad:PI/4f64};
pub const ANGLE90:Angle=Angle{rad:PI/2f64};
pub const ANGLE180:Angle=Angle{rad:PI};
#[derive(Debug,PartialEq,PartialOrd,Clone,Copy)]
pub struct Angle{
rad:f64,
}
impl Angle{
//构造函数(弧度) (x,y)
pub fn new(rad:f64)->Angle{//建议调整到(-π,π)
Angle{rad:rad}
}
pub fn from(x:f64,y:f64)->Angle{//建议调整到(-π,π)
Angle{rad:y.atan2(x)}
}
//属性 弧度 角度 x y 单位矢量
pub fn get_radian(&self)->f64{
self.rad
}
pub fn set_radian(& mut self,rad:f64)->(){
self.rad=rad;
}
pub fn get_degree(&self)->f64{
self.rad*(180f64/PI)
}
pub fn set_degree(&mut self,d:f64)->(){
self.rad=d*(PI/180f64);
}
pub fn unit_x(&self)->f64{
self.rad.cos()
}
pub fn unit_y(&self)->f64{
self.rad.sin()
}
}
//运算符重载 + - * /,实现加减及比例缩放
impl Add for Angle{
type Output = Self;
fn add(self, other: Self) ->Angle{
Self{rad:self.rad + other.rad}
}
}
impl Sub for Angle{
type Output = Self;
fn sub(self, other: Self) ->Angle{
Self{rad:self.rad - other.rad}
}
}
impl Mul<f64> for Angle{
type Output = Self;
fn mul(self, scale:f64) -> Angle {
Angle::new(self.rad * scale)
}
}
impl Div<f64> for Angle{
type Output = Self;
fn div(self, scale:f64) -> Angle {
Angle::new(self.rad / scale)
}
}
#[test]
fn my_test() {
assert_eq!(ANGLE0.rad,0f64);
assert_eq!(Angle::new(0f64),ANGLE0);
assert_eq!(Angle::from(1f64,1f64),ANGLE45);
assert_eq!(Angle::new(PI/2f64),ANGLE90);
assert_eq!(Angle::new(PI),ANGLE180);
let mut a=ANGLE0;
a.set_degree(90f64);
assert_eq!(a.get_radian(),PI/2f64);
a.set_radian(PI);
assert_eq!(a.get_degree(),180f64);
a=Angle::from(1f64,1f64);
assert_eq!(a.get_degree(),45f64);
assert_eq!(a.unit_y()/a.unit_x(),1f64);
assert_eq!(ANGLE45+ANGLE45,ANGLE180-ANGLE90);
assert_eq!(ANGLE45*2f64,ANGLE180/2f64);
}