0

Go 的接口(interface)和 Rust 的特征(Trait)是经常被放在一起做比较的概念。咱可以用它们来实现计算不同几何形状的面积和周长的功能。

Go

type geometry interface {
 area() float64
 perim() float64
}
type rect struct {
 width, height float64
}
type circle struct {
 radius float64
}
func (r rect) area() float64 {
 return r.width * r.height
}
func (r rect) perim() float64 {
 return 2*r.width + 2*r.height
}
func (c circle) area() float64 {
 return math.Pi * c.radius * c.radius
}
func (c circle) perim() float64 {
 return 2 * math.Pi * c.radius
}
func measure(g geometry) {
 fmt.Println(g)
 fmt.Println(g.area())
 fmt.Println(g.perim())
}
func main() {
 r := rect{width: 3, height: 4}
 c := circle{radius: 5}
 
 measure(r)
 measure(c)
}

Rust

use core::f64::consts::PI;
use core::fmt::Debug;
trait Geometry {
 fn area(&self) -> f64;
 fn perim(&self) -> f64;
}
#[derive(Debug)]
struct Rect {
 width: f64,
 height: f64,
}
#[derive(Debug)]
struct Circle {
 radius: f64,
}
impl Geometry for Rect {
 fn area(&self) -> f64 {
 self.width * self.height
 }
 fn perim(&self) -> f64 {
 2.0 * self.height + 2.0 * self.width
 }
}
impl Geometry for Circle {
 fn area(&self) -> f64 {
 PI * self.radius * self.radius
 }
 fn perim(&self) -> f64 {
 2.0 * PI * self.radius
 }
}
fn main() {
 fn measure<T>(g: &T)
 where T: Geometry + Debug {
 println!("{:?}", g);
 println!("{:?}", g.area());
 println!("{:?}", g.perim());
 }
 
 let r = Rect{width: 3.0, height: 4.0};
 let c = Circle{radius: 5.0};
 
 measure(&r);
 measure(&c);
}

Ljzn
407 声望103 粉丝

尽量减少神经质的时间


引用和评论

0 条评论
评论支持部分 Markdown 语法:**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用。你还可以使用 @ 来通知其他用户。

AltStyle によって変換されたページ (->オリジナル) /