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, ...);
发布了132 篇原创文章 · 获赞 135 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/lcloveyou/article/details/104761829