💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
[TOC] ### 使用Rust求两个点之间的距离 ![](https://img.kancloud.cn/88/3d/883de41b8d9440c3ce76dd182be5dcb5_511x366.png) #### 使用普通的方式 ```rust //求两个点之间的距离 struct Point(f32, f32); fn distance(p1: Point, p2: Point) -> f32 { let dis = (p2.0 - p1.0) * (p2.0 - p1.0) + (p2.1 - p1.1) * (p2.1 - p1.1); dis.sqrt() } fn main() { let p1 = Point(0.0, 0.0); let p2 = Point(3.0, 4.0); println!("{}", distance(p1, p2)); } ``` #### 使用面向对象方式 ```rust //求两个点之间的距离 struct Point(f32, f32); impl Point{ fn distance(&self,p:Point) -> f32 { let dis = (self.0 - p.0) * (self.0 - p.0) + (self.1 - p.1) * (self.1 - p.1); dis.sqrt() } } fn main() { let p1 = Point(0.0, 0.0); let p2 = Point(3.0, 4.0); //println!("{}", distance(p1, p2)); println!("{}", p2.distance(p1)); } ``` ![](https://img.kancloud.cn/8a/66/8a66b8c4b1b4e0fe8f3075cca1733e73_777x136.png)