該程序之所以死是因為無限遞歸: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 回答
- 0 關注
- 533 瀏覽
添加回答
舉報
0/150
提交
取消