助力软件开发企业降本增效 PHP / java源码系统,只需一次付费,代码终身使用! 广告
[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)