Rust 教程
- 第1节:Rust 介绍
- 第2节:Rust 安装
- 第3节:Rust Hello,world!
- 第4节:Rust Hello,Cargo!
- 第5节:Rust 栈和堆
- 第6节:Rust 测试
- 第7节:Rust 条件编译
- 第8节:Rust 文档
- 第9节:Rust 迭代器
- 第10节:Rust 并发性
- 第11节:Rust 错误处理
- 第12节:Rust 外部函数接口
- 第13节:Rust Borrow 和 AsRef
- 第14节:Rust 发布通道
- 第15节:Rust 变量绑定
- 第16节:Rust 函数
- 第17节:Rust 基本类型
- 第18节:Rust 注释
- 第19节:Rust if
- 第20节:Rust for 循环
- 第21节:Rust while 循环
- 第22节:Rust 所有权
- 第23节:Rust 引用与借用
- 第24节:Rust 生存期
- 第25节:Rust 可变性
- 第26节:Rust 结构体
- 第27节:Rust 枚举
- 第28节:Rust 匹配
- 第29节:Rust 模式
- 第30节:Rust 方法语法
- 第31节:Rust 向量
- 第32节:Rust 字符串
- 第33节:Rust 泛型
- 第34节:Rust 特征
- 第35节:Rust 降
- 第36节:Rust if let
- 第37节:Rust 特征的对象
- 第38节:Rust 闭包
- 第39节:Rust 通用函数调用语法
- 第40节:Rust 箱和模块
- 第41节:Rust “常量”和“静态”
- 第42节:Rust 属性
- 第43节:Rust type 别名
- 第44节:Rust 类型转换
- 第45节:Rust 关联类型
- 第46节:Rust 全类型
- 第47节:Rust 操作符和重载
- 第48节:Rust 'Deref'强制转换
- 第49节:Rust 宏命令
- 第50节:Rust 原始指针
- 第51节:Rust unsafe
Rust 通用函数调用语法
通用函数调用语法
有时,函数可以有相同的名字。看看下面这段代码:
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.f(),我们就会得到一个错误:
error: multiple applicable methods in scope [E0034]
b.f();
note: candidate #1 is defined in an impl of the trait `main::Foo` for the type
`main::Baz`
fn f(&self) { println!("Baz’s impl of Foo"); }
note: candidate #2 is defined in an impl of the trait `main::Bar` for the type
`main::Baz`
fn f(&self) { println!("Baz’s impl of Bar"); }
我们需要一种消除歧义的方法。这种方法称为“通用函数调用语法”,它这种语法看起来是下面这样的:
Foo::f(&b);
Bar::f(&b);
我们让它停止一下。
Foo::
Bar::
这些部分调用的类型有两个特征:Foo 和 Bar。这最终实际上是做了两者之间的消歧:Rust 从两者中调用你所使用的特征名称。
f(&b)
当我们用 method syntax()调用一个方法比如 b.f(),如果 f() 含有 &self,Rust 会自动 borrow b。在本例这种情况下,Rust 不会,所以我们需要传递一个具体的 &b。
尖括号形式
现在我们谈论一下 UFCS 形式:
Trait::method(args);
这只是一种速记收手法。下面是在某些情况下需要使用的扩展形式:
<Type as Trait>::method(args);
< >::
语法是一种提供类型提示的方法。类型写在 < >s
里面。在本例中,类型是 Type as Trait 表明我们希望特征的方法在这里被调用。在不出现歧义的情况下,特征部分是可选的。这同样适用于用尖括号括,因此要用较短的形式。
这是使用更长形式的一个例子:
trait Foo {
fn clone(&self);
}
#[derive(Clone)]
struct Bar;
impl Foo for Bar {
fn clone(&self) {
println!("Making a clone of Bar");
<Bar as Clone>::clone(self);
}
}
这将调用 Clone 特征的 Clone () 方法,而不是 Foo 特征的方法。