Rust 编程视频教程(进阶)——026_3 高级 trait3

视频地址

头条地址:https://www.ixigua.com/i6775861706447913485
B站地址:https://www.bilibili.com/video/av81202308/

源码地址

github地址:https://github.com/anonymousGiga/learn_rust

讲解内容

完全限定语法
(1)同名的方法

trait A{ 
	fn print(&self);
} 
trait B{ 
	fn print(&self); 
} 
struct MyType; 
impl A for MyType{ 
	fn print(&self) { 
		println!("A print for MyType");
	}
} 
impl B for MyType{ 
	fn print(&self) { 
		println!("B print for MyType"); 
	} 
} 
impl MyType{ 
	fn print(&self) { 
		println!("MyType");
	} 
}
fn main() {
	let my_type = MyType;
	my_type.print(); //等价于MyType::print(&my_type);
	A::print(&my_type);
	B::print(&my_type);
	println!("Hello, world!");
}

说明:上述例子中,方法获取一个 self 参数,如果有两个 类型 都实现了同一 trait,Rust 可以根据 self 的类型计算出应该使用哪一个 trait 实现。(使用my_type.print(),print方法根据里面的self类型知道具体调用哪个方法)

(2)对关联函数的完全限定语法
例子:

trait Animal { 
	fn baby_name() -> String;
} 
struct Dog; 
impl Dog { 
	fn baby_name() -> String { 
		String::from("Spot") 
	} 
} 
impl Animal for Dog { 
	fn baby_name() -> String { 
		String::from("puppy")
	} 
} 
fn main() { 
	println!("A baby dog is called a {}", Dog::baby_name());
	//println!("A baby dog is called a {}", 	
	Animal::baby_name());//报错,如何处理? 
}

正确的调用方式:

fn main() { 
	println!("A baby dog is called a {}", Dog::baby_name());
	println!("A baby dog is called a {}", 
			<Dog as Animal>::baby_name());//完全限定语法 
}

完全限定语法定义为:

<Type as Trait>::function(receiver_if_method, next_arg, ...);
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值