[英]can't use implemented trait in other file rust
所以我有兩個文件 main.rs 和 utils.rs
我在 utils.rs 上實現了 StringUtils 方法,但是當我嘗試在 main.rs 中使用該方法時,它給了我這個錯誤
error[E0599]: no method named `slice` found for reference `&str` in the current scope --> src\main.rs:89:50 | 89 | let text: String = self.inner.clone().as_str().slice(self.start, self.current); | ^^^^^ method not found in `&str` | = help: items from traits can only be used if the trait is implemented and in scope note: `StringUtils` defines an item `slice`, perhaps you need to implement it --> src\util.rs:25:1 | 25 | trait 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?
在 Rust 編程語言中的模塊樹中引用項目的路徑部分中出現了一個實質上等效的示例(如果您還沒有閱讀,我建議您閱讀)。
簡短的版本是您希望其他模塊可見的模塊中的任何項目(例如,特征,function 定義)應該具有pub
可見性修飾符的某種變體。 在您的即時示例中,這表明需要制作StringUtils
特征pub
(或將其暴露給包含模塊的其他一些變體)。
事實上,如果您嘗試通過use utils::StringUtils
而不是 glob 導入直接導入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 {
| ^^^^^^^^^^^^^^^^^
這將鏈接到對一種修復方法的解釋。 因此,如果我們改為執行pub trait StringUtils {... }
,則沒有與使用該特征相關的問題。
您仍然會遇到@trentcl 提到的關於slice
的參數數量不正確的問題,我認為self.start..self.current
(或包含版本)應該是傳遞的范圍。
最后,有一個與text
類型注釋相關的錯誤,因為StringUtils::slice
將返回&str
,而不是String
。 根據您的需要,您應該更改特征及其實現,或者查看go between &str and String的方法以及它們之間的差異。
( 游樂場)。
您可能希望有一個更嚴格的可見性修飾符,例如pub(crate)
或pub(super)
分別限制對包含板條箱或包含模塊的可見性。
可以在 The Rust Reference 的相關部分中找到對此的更詳盡的解釋。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.