Rust从入门到实战系列二百九十二:定义默认的泛型类型参数

当我们使用泛型类型参数时,可以为该泛型参数指定一个具体的默认类型,这样当实现该特征时,如果该
默认类型可以使用,那用户再无需手动指定具体的类型。
2. 🌟🌟
use std::ops::Sub;
#[derive(Debug, PartialEq)]
struct Point {
x: T,
y: T,
}
// 用 三 种 方 法 填 空: 其 中 两 种 使 用 默 认 的 泛 型 参 数 , 另 外 一 种 不 使 用
impl __ {
type Output = Self;
fn sub(self, other: Self) -> Self::Output {
Point {
x: self.x - other.x,
y: self.y - other.y,
}
}
}
fn main() {
assert_eq!(Point { x: 2, y: 3 } - Point { x: 1, y: 0 },
Point { x: 1, y: 3 });
println!(“Success!”)
}
完全限定语法
在 Rust 中,两个不同特征的方法完全可以同名,且你可以为同一个类型同时实现这两个特征。这种情况
下,就出现了一个问题:该如何调用这两个特征上定义的同名方法。为了解决这个问题,我们需要使用完
全限定语法( Fully Qualified Syntax )。
示例
trait UsernameWidget {
fn get(&self) -> String;
}
trait AgeWidget {
fn get(&self) -> u8;
}
struct Form {
username: String,
age: u8,
}
impl UsernameWidget for Form {
fn get(&self) -> String {
self.username.clone()
}
}
impl AgeWidget for Form {
fn get(&self) -> u8 {
self.age
}
}
fn main() {
let form = Form{
username: “rustacean”.to_owned(),
age: 28,
};
// 如 果 你 反 注 释 下 面 一 行 代 码 , 将 看 到 一 个 错 误: Fully Qualified Syntax
// 毕 竟 , 这 里 有 好 几 个 同 名 的 get 方 法
//
// println!(“{}”, form.get());
l t U Wid t t(&f )
let username = UsernameWidget::get(&form);
assert_eq!(“rustacean”.to_owned(), username);
let age = AgeWidget::get(&form); // 你 还 可 以 使 用 以 下 语 法 <Form as AgeWidget>::get
assert_eq!(28, age);
println!(“Success!”)
}
练习题
3. 🌟🌟
trait Pilot {
fn fly(&self) -> String;
}
trait Wizard {
fn fly(&self) -> String;
}
struct Human;
impl Pilot for Human {
fn fly(&self) -> String {
String::from(“This is your captain speaking.”)
}
}
impl Wizard for Human {
fn fly(&self) -> String {
String::from(“Up!”)
}
}
impl Human {
fn fly(&self) -> String {
String::from(“waving arms furiously”)
}
}
fn main() {
let person = Human;
assert_eq!(, “This is your captain speaking.”);
assert_eq!(
, “Up!”);
assert_eq!(__, “waving arms furiously”);
println!(“Success!”)
}

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值