rust 泛型

struct Val<T> {
val: T,
}

impl<T> Val<T> {
fn value(&self) -> &T {
&self.val
}
}


fn main() {
let x = Val{ val: 3.0 };
let y = Val{ val: "hello".to_string()};
println!("{}, {}", x.value(), y.value());
}

 ========================================================================

fn multiply<T:std::ops::Mul<Output=T>>(a:T, b:T)->T{
a*b
}

fn main() {
assert_eq!(6, multiply(2u8, 3u8));
assert_eq!(5.0, multiply(1.0, 5.0));

println!("Success!")
}

 

========================================================================

struct Point<T> {
x: T,
y: T,
}

impl Point<f32> {
fn distance_from_origin(&self) -> f32 {
(&self.x.powi(2) + &self.y.powi(2)).sqrt()
}
}

fn main() {
let p = Point{x: 5.0_f32, y: 10.0_f32};
println!("{}",p.distance_from_origin())
}

 

========================================================================

 

 

// `Centimeters`, 一个元组结构体,可以被比较大小
#[derive(PartialEq, PartialOrd)]
struct Centimeters(f64);

// `Inches`, 一个元组结构体可以被打印
#[derive(Debug)]
struct Inches(i32);

impl Inches {
fn to_centimeters(&self) -> Centimeters {
let &Inches(inches) = self;

Centimeters(inches as f64 * 2.54)
}
}

// 添加一些属性让代码工作
// 不要修改其它代码!
#[derive(Debug, PartialEq, PartialOrd)]
struct Seconds(i32);

fn main() {
let _one_second = Seconds(1);

println!("One second looks like: {:?}", _one_second);
let _this_is_true = _one_second == _one_second;
let _this_is_true = _one_second > _one_second;

let foot = Inches(12);

println!("One foot equals {:?}", foot);

let meter = Centimeters(100.0);

let cmp =
if foot.to_centimeters() < meter {
"smaller"
} else {
"bigger"
};

println!("One foot is {} than one meter.", cmp);
}

posted @ 2022-07-09 21:43  CrossPython  阅读(49)  评论(0)    收藏  举报