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 @   CrossPython  阅读(44)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示