[英]How to call a method when a trait and struct use the same method name?
该程序之所以死是因为无限递归:
use std::any::Any;
trait Foo {
fn get(&self, index: usize) -> Option<&Any>;
}
impl Foo for Vec<i32> {
fn get(&self, index: usize) -> Option<&Any> {
Vec::get(self, index).map(|v| v as &Any)
}
}
fn main() {
let v: Vec<i32> = vec![1, 2, 4];
println!("Results: {:?}", v.get(0))
}
编译器本身对此发出警告:
warning: function cannot return without recurring
--> src/main.rs:8:5
|
8 | fn get(&self, index: usize) -> Option<&Any> {
| _____^ starting here...
9 | | Vec::get(self, index).map(|v| v as &Any)
10 | | }
| |_____^ ...ending here
|
= note: #[warn(unconditional_recursion)] on by default
note: recursive call site
--> src/main.rs:9:9
|
9 | Vec::get(self, index).map(|v| v as &Any)
| ^^^^^^^^^^^^^^^^^^^^^
= help: a `loop` may express intention better if this is on purpose
为什么在这种情况下通用调用语法不起作用? 编译器无法理解我要调用Vec::get
而不是Foo::get
。
如果我不想更改函数名称,该如何解决?
要指定要调用的方法(是固有的还是由特征提供的),您要使用完全限定的语法 :
Type::function(maybe_self, needed_arguments, more_arguments)
Trait::function(maybe_self, needed_arguments, more_arguments)
您的案例不起作用,因为Vec
没有名为get
的方法 ! 从Deref
实现向[T]
提供get
。
最简单的解决方法是直接调用as_slice
:
self.as_slice().get(index).map(|v| v as &Any)
您也可以使用完全限定的语法,这种情况下需要使用尖括号( <...>
),以避免在声明数组文字时产生歧义:
<[i32]>::get(self, index).map(|v| v as &Any)
通用调用语法
请注意,尽管Rust最初使用术语通用函数调用语法(UFCS),但该术语的使用与现有的已理解编程术语冲突,因此不建议使用它。 替换术语是完全限定的语法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.