你可以使用 type 关键字声明另一类型的别名:type Name = String;然后,你可以就像使用一个真正的类型一样使用这种类型:type Name = String;let x: Name = "Hello".to_string();但是请注意,这是一个别名,不完全是一个新类型。换句话说,因为 Rust 是强类型的,所以你不能比较两个不同类型:let x: i32 = 5;let y: i64 = 5;if x == y { // ...
有时,函数可以有相同的名字。看看下面这段代码:trait Foo {fn f(&self);}trait Bar {fn f(&self);}struct Baz;impl Foo for Baz {fn f(&self) { println!("Baz’s impl of Foo"); }}impl Bar for Baz {fn f(&self) { println!("Baz’s impl of Bar"); }}let b = Baz;如果我们试图调用 b.
函数很好,但是如果你想要在一些数据上调用很多函数,那是非常不合适的。请思考以下代码: baz(bar(foo)));我们从左往右读这些代码,就会看到 ‘baz bar foo’。但是这并不是我们由内-外调用函数的顺序:‘foo bar baz’。如果我们这样写,会不会更好? foo.bar().baz();幸运的是,你可能已经猜到了,关于上面问题的答案,可以!