Calling instance function within threads
⚓ Rust 📅 2025-09-14 👤 surdeus 👁️ 10I'm fairly new to RUST. I have the following example, where I don't understand why you can call an instance function in a thread, but then can't call another instance function in the first instance function.
Code example:
use std::thread;
struct Greeter {
name: String,
i: u32,
}
impl Greeter {
fn greet(&self, i: u32 ) {
println!("Hello from {}", self.name);
println!("Number is: {}", i );
let handle = thread::spawn( move || {
self.print(); // greeter is moved into the thread, so we can call its method
});
handle.join().unwrap();
}
fn print(&self) {
println!("In PRINT function.");
}
}
fn main() {
let greeter = Greeter {
name: "MyName".to_string(),
i: 1,
};
greeter.greet( 32 ); // `greeter` is moved into the thread, so we can call its method
}
1 post - 1 participant
🏷️ Rust_feed