相关疑难解决方法(0)

当trait和struct使用相同的方法名时,如何调用方法?

该程序因无限递归而死亡:

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))
}
Run Code Online (Sandbox Code Playgroud)

编译器本身警告:

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 | | …
Run Code Online (Sandbox Code Playgroud)

rust

11
推荐指数
1
解决办法
3342
查看次数

标签 统计

rust ×1