pub trait Walk {
fn walk(&self);
}
底下則定義了一個 struct 並實做了 Walk trait。
use crate::action::Walk;
pub struct Robot {
}
impl Walk for Robot {
fn walk(&self) {
println!("Walk");
}
}
程式的組成結構為
- Cargo.toml
- src/
- main.rs
- robot/
- mod.rs (定義了 struct Robot, 並實做 Walk)
- action/
- mod.rs (定義了 Trait Walk)
mod robot;
mod action;
use crate::robot::Robot;
fn main() {
let robot = Robot {
};
robot.walk();
}
雖然 struct Robot 與 Walk 的實做在同一個 rs 檔案中。
但編譯卻會出現以下錯誤。
Compiling rust_trait v0.1.0 (/tmp/rust_trait) error[E0599]: no method named `walk` found for struct `Robot` in the current scope --> src/main.rs:10:10 | 10 | robot.walk(); | ^^^^ method not found in `Robot` | ::: src/robot/mod.rs:3:1 | 3 | pub struct Robot { | ---------------- method `walk` not found for this struct | ::: src/action/mod.rs:2:7 | 2 | fn walk(&self); | ---- the method is available for `Robot` here | = help: items from traits can only be used if the trait is in scope help: the following trait is implemented but not in scope; perhaps add a `use` for it: | 1 + use crate::action::Walk; | For more information about this error, try `rustc --explain E0599`. error: could not compile `rust_trait` (bin "rust_trait") due to previous error錯誤訊息說明說雖然 Robot 有實做了 Walk Trait, 但 main 本身沒有引入 Walk trait, 因此無法使用。需要將程式改為
mod robot;
mod action;
use crate::robot::Robot;
use crate::action::Walk;
fn main() {
let robot = Robot {
};
robot.walk();
}
這邊在 main 中引入了 Walk Trait 後,在 Robot 中實做的 walk 才能正確使用。 也就是說如果一個 struct 實做了 20 個 trait,那麼想完整使用每個 trait 的 function,需要額外再引入 20 個 trait...。
會這麼設計的理由可能是希望寫的人能夠清楚知道自己在作什麼,需要什麼東西。若編譯器沒有提示功能,使用起來感覺蠻痛苦的...。
沒有留言:
張貼留言