【问题标题】:How to call a method when a trait and struct use the same method name?当 trait 和 struct 使用相同的方法名时如何调用方法?
【发布时间】:2017-11-10 18:13:51
【问题描述】:

这个程序因为无限递归而死:

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

如果我不想更改函数名称,该如何解决?

【问题讨论】:

    标签: rust


    【解决方案1】:

    要指定调用哪个方法,无论是固有的还是从特征提供的,您想使用fully qualified syntax

    Type::function(maybe_self, needed_arguments, more_arguments)
    Trait::function(maybe_self, needed_arguments, more_arguments)
    

    您的情况不起作用,因为Vec 没有名为get的方法getDeref implementation to [T] 提供。

    最简单的解决方法是直接调用as_slice

    self.as_slice().get(index).map(|v| v as &Any)
    

    您还可以使用在这种情况下需要尖括号的完全限定语法 (&lt;...&gt;) 以避免声明数组字面量时出现歧义:

    <[i32]>::get(self, index).map(|v| v as &Any)
    

    通用调用语法

    请注意,虽然 Rust 最初使用术语通用函数调用语法 (UFCS),但该术语的使用与现有理解的编程术语相冲突,因此不建议使用它。替换术语是完全限定的语法。

    【讨论】:

    • 如果是Deref&lt;Vec&lt;i32&gt; as Deref&gt;::get(self, index) 也可以吗?
    • @user1244932 一个有趣的问题,但事实并非如此。这个语法的重点是明确的,所以&lt;T as Deref&gt; 意味着“只有Deref trait 上的方法”,但get 不是这样的方法。
    猜你喜欢
    • 2022-10-06
    • 2016-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-20
    相关资源
    最近更新 更多