error[E0599]: no method named 'x' found for struct
Rustで構造体に存在しないメソッドを呼び出した際のコンパイルエラー
概要
Rustで構造体やenum、プリミティブ型に対して、定義されていないメソッドを呼び出そうとした際に発生するコンパイルエラーです。
エラーメッセージ
error[E0599]: no method named `foo` found for struct `MyStruct` in the current scope
--> src/main.rs:10:5
|
5 | struct MyStruct;
| --------------- method `foo` not found for this struct
...
10 | s.foo();
| ^^^ method not found in `MyStruct`
原因
- メソッドの未実装: implブロックでメソッドを定義していない
- トレイトのインポート忘れ: トレイトのメソッドを使用するにはuseが必要
- 可視性の問題: メソッドがpubでない
- 型の不一致: 期待した型と異なる
- タイプミス: メソッド名のスペルミス
解決策
1. implブロックでメソッドを定義
| |
2. トレイトをインポート
| |
3. トレイトを実装
| |
4. 参照とデリファレンス
| |
5. ジェネリクスとトレイト境界
| |
6. derive マクロを使用
| |
7. Option/Resultのメソッド
| |
よくある間違い
- イテレータのメソッドを使うのに
use std::iter::Iteratorを忘れる(通常は自動) &strとStringのメソッドの違いを混同する- トレイトオブジェクト(
dyn Trait)でサイズが必要なメソッドを呼ぶ
関連エラー
参考リンク
Rust の他のエラー
cannot borrow as mutable because it is also borrowed as immutable
called `Option::unwrap()` on a `None` value
error[E0382]: borrow of moved value
error[E0507]: cannot move out of 'x' which is behind a shared reference
Rust: cannot borrow as mutable
Rust: cannot borrow as mutable because it is also borrowed as immutable
この記事は役に立ちましたか?