mod & use 应该如何处理 Rust 中的 trait?

Dou*_*oug 4 rust

考虑以下人为的情况:

mod imported {
    pub trait Imported {
        fn hello(&self, x:int) -> int;
    }
}

struct Hi;

impl imported::Imported for Hi {
    fn hello(&self, x:int) -> int {
        return x;
    }
}

#[test]
fn test_thing() {
    let value = Hi;
    println!("{:?}", value.hello(10));
}
Run Code Online (Sandbox Code Playgroud)

这不会编译,因为特征导入不在范围内,所以方法 hello() 不能被调用:

imports.rs:20:18: 20:33 error: type `imports::Hi` does not implement any method in scope named `hello`
imports.rs:20   println!("{:?}", value.hello(10));
                                 ^~~~~~~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)

如果我们将 Imported 放在当前范围内(即摆脱 mod 导入),这可以正常工作,但像这样,它不会。

通常为此目的,您将使用 'use' 将 'Imported' 符号带入本地范围:

use imported::Imported; 
Run Code Online (Sandbox Code Playgroud)

但是,在这种情况下,您不能,因为文件开头尚不存在符号“导入”:

imports.rs:2:5: 2:13 error: unresolved import. maybe a missing `extern crate imported`?
imports.rs:2 use imported::Imported;
                 ^~~~~~~~
imports.rs:2:5: 2:23 error: failed to resolve import `imported::Imported`
imports.rs:2 use imported::Imported;
                 ^~~~~~~~~~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)

在 mod 导入调用之后你不能这样做,因为:

imports.rs:8:1: 8:24 error: `use` and `extern crate` declarations must precede items
imports.rs:8 use imported::Imported;
             ^~~~~~~~~~~~~~~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)

公平地说,这只发生在您实现一个特征然后尝试在安全文件中使用该 impl 时,但似乎这实际上是一个非常常见的测试用例。

您可以通过稍微不同地构建代码并从一些公共父级导入模块来解决它,但这似乎是当前系统的固有限制。

我错过了什么吗?

Chr*_*gan 5

我想你确实错过了一些东西。use imported::Imported;在文件顶部添加确实有效 - 我认为这不是您试图编译的内容。

use语句虽然写在mod语句之前,但是在mod之后解决,所以不存在源码顺序问题。

我认为您的错误实际上是您的文件imports.rs不是板条箱根。请记住,如果您不使用或,则use语句采用绝对路径。要使其在任何地方工作,您需要编写; 假设您正在编译一个包含,您将需要,特征的绝对路径。superselfuse self::imported::Imported;lib.rsmod imports;use imports::imported::Imported

(顺便说一句,你可以return x;在函数的末尾用 替换x。记住 Rust 的块值原则,块中的最后一个表达式是块的值。)