【问题标题】:can't use implemented trait in other file rust无法在其他文件 rust 中使用已实现的特征
【发布时间】:2021-08-18 19:03:22
【问题描述】:

所以我有两个文件 main.rs 和 utils.rs

我在 utils.rs 上实现了 StringUtils 方法,但是当我尝试在 main.rs 中使用该方法时 它给了我这个错误

错误[E0599]:在当前范围内没有找到用于引用 `&str` 的名为 `slice` 的方法
  --> src\main.rs:89:50
   |
89 |让文本: String = self.inner.clone().as_str().slice(self.start, self.current);
   | ^^^^^ 在 `&str` 中找不到方法
   |
   =帮助:只有在实现了特征并且在范围内时才能使用特征中的项目
注意:`StringUtils`定义了一个`slice`项,也许你需要实现它
  --> src\util.rs:25:1
   |
25 |特征 StringUtils {
   | ^^^^^^^^^^^^^^^^^
// main.rs

mod utils;
use utils::*;

...

    fn add_token0(&mut self, token_type: TokenType) {
        let text: String = self.inner.clone().as_str().slice(self.start, self.current);
        // error: no method named `slice` found for reference `&str` in the current scope
    }

...

但我已经在 utils.rs 上实现了它

// utils.rs

...

trait StringUtils {
    ...
    fn slice(&self, range: impl RangeBounds<usize>) -> &str;
    ...
}

impl StringUtils for str {
    ...
    fn slice(&self, range: impl RangeBounds<usize>) -> &str {
        ...
    }
    ...
}

...

为什么我的实现不起作用,有什么办法可以解决或者我只能在 main.rs 上实现 StringUtils?

【问题讨论】:

  • 您是否打算公开 StringUtils 特征(对您的 crate 或其他 crate 中的其他模块)?
  • slice 应该接受多少个参数?您使用 2 个参数(selfrange)定义了它,但您使用 3 个参数(隐式 selfself.startself.current)调用它
  • @kopecs 是的,我在问这个问题
  • @trentcl 感谢您的提醒,尽管它仍然没有给出未找到方法的错误

标签: rust namespaces implementation


【解决方案1】:

Rust 编程语言中的 Paths for Referring to an Item in the Module Tree 部分出现了一个实质上等效的示例(如果您还没有阅读,我建议您阅读)。

简短的版本是,模块中您希望其他模块可见的任何项目(例如,特征、函数定义)都应该具有 pub 可见性修饰符的一些变体。在您的即时示例中,这表明需要制作 StringUtils 特征 pub (或将其暴露给包含模块的其他变体)。

事实上,如果您尝试通过use utils::StringUtils 直接导入StringUtils 而不是全局导入,则会收到以下错误消息:

error[E0603]: trait `StringUtils` is private
  --> src/lib.rs:7:12
   |
7  | use utils::StringUtils;
   |            ^^^^^^^^^^^ private trait
   |
note: the trait `StringUtils` is defined here
  --> src/lib.rs:19:5
   |
19 |     trait StringUtils {
   |     ^^^^^^^^^^^^^^^^^

这将链接到this explanation 的一种修复方法。因此,如果我们改为使用 pub trait StringUtils { ... },则不会出现与使用 trait 相关的问题。

你仍然会遇到@trentcl 提到的关于slice 的参数数量不正确的问题,我认为self.start..self.current(或包含的版本)应该是传递的范围。

最后,与text 的类型注释有关的错误,因为StringUtils::slice 将返回&amp;str,而不是String。根据您的需要,您应该更改 trait 及其实现,或者查看 ways to go between &str and Stringdifferences between them

(playground).


您可能希望有一个更具限制性的可见性修饰符,例如 pub(crate)pub(super),它们分别限制包含板条箱或包含模块的可见性。

可以在the relevant section in The Rust Reference 中找到更详尽的解释。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-29
    • 2022-12-07
    • 1970-01-01
    • 1970-01-01
    • 2020-08-15
    • 2021-08-20
    • 2022-08-15
    • 2016-06-02
    相关资源
    最近更新 更多