前提
Rust言語のThreadの練習をしています。
そこでSample構造体のメソッドをthread::spawn()で呼び出そうとしたのですが以下のエラーが発生しました
発生している問題・エラーメッセージ
error[E0593]: function is expected to take 0 arguments, but it takes 1 argument --> src\main.rs:28:23 | 19 | fn process1(&self) { | ------------------ takes 1 argument ... 28 | thread::spawn(Self::process1); | ------------- ^^^^^^^^^^^^^^ expected function that takes 0 arguments | | | required by a bound introduced by this call | note: required by a bound in `spawn` --> C:\Users\LatteSyobon\.rustup\toolchains\stable-x86_64-pc-windows-msvc\lib/rustlib/src/rust\library\std\src\thread\mod.rs:620:8 | 620 | F: FnOnce() -> T, | ^^^^^^^^^^^^^ required by this bound in `spawn`
該当のソースコード
Rust
1use std::thread; 2 3fn main() { 4 let s = Sample::new(); 5 s.run(); 6} 7 8pub struct Sample { 9 10} 11 12impl Sample { 13 pub fn new() -> Self { 14 Self { 15 16 } 17 } 18 19 fn process1(&self) { 20 println!("Hello from Process1") 21 } 22 23 fn process2(&self) { 24 println!("Hello from Process2") 25 } 26 27 pub fn run(&self) { 28 thread::spawn(Self::process1); 29 thread::spawn(Self::process2); 30 } 31}
試したこと
引数として&selfを渡すように言われているのはわかるのですが、そこで以下のようにしてみると
Rust
1// ~~~~ 2pub fn run(&self) { 3 thread::spawn(Self::process1(self)); 4 thread::spawn(Self::process2(self)); 5} 6// ~~~~
次は以下のようなエラーが出てしまいます
error[E0277]: expected a `FnOnce<()>` closure, found `()` --> src\main.rs:28:23 | 28 | thread::spawn(Self::process1(self)); | ------------- ^^^^^^^^^^^^^^^^^^^^ expected an `FnOnce<()>` closure, found `()` | | | required by a bound introduced by this call | = help: the trait `FnOnce<()>` is not implemented for `()` = note: wrap the `()` in a closure with no arguments: `|| { /* code */ }` note: required by a bound in `spawn` --> C:\Users\LatteSyobon\.rustup\toolchains\stable-x86_64-pc-windows-msvc\lib/rustlib/src/rust\library\std\src\thread\mod.rs:620:8 | 620 | F: FnOnce() -> T, | ^^^^^^^^^^^^^ required by this bound in `spawn`
この場合どのようにすれば良いのでしょうか?
補足情報(FW/ツールのバージョンなど)
- Rustc 1.57
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/04/03 12:19