为了账号安全,请及时绑定邮箱和手机立即绑定

特征和结构使用相同的方法名称时如何调用方法?

特征和结构使用相同的方法名称时如何调用方法?

Git
LEATH 2019-12-06 11:14:21
该程序之所以死是因为无限递归: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 defaultnote: 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。如果我不想更改函数名称,该如何解决?
查看完整描述

1 回答

  • 1 回答
  • 0 关注
  • 468 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信