前言:我已经进行了研究,知道单独使用全局变量不是一个好主意,也不符合Rust的惯用法。非常乐意听取其他解决此问题的建议。
背景:我有一个控制台应用程序,连接到websocket后,服务器会发送“已连接”消息。发送方和接收方是分开的线程,一切都运作良好。在connect()
调用之后,循环开始,并在终端中放置提示,表示应用程序已准备好从用户接收输入。
问题:问题在于当前的执行流程调用连接,然后立即显示提示,然后应用程序接收来自服务器的连接成功消息。
在其他高级语言中如何解决:设置一个全局布尔值(我们称其为ready
),一旦应用程序“准备就绪”,就显示提示。
我认为在Rust中可能会是这样:
//Possible global ready flag with 3 states (true, false, None)
let ready: Option<&mut bool> = None;
fn main(){
welcome_message(); //Displays a "Connecting..." message to the user
//These are special callback I created and basically when the
//message is received the `connected` is called.
//If there was an error getting the message (service is down)
//then `not_connected` is called. *This is working code*
let p = mylib::Promise::new(connected, not_connected);
//Call connect and start websocket send and receive threads
mylib::connect(p);
//Loop for user input
loop {
match ready {
Some(x) => {
if x == true { //If ready is true, display the prompt
match prompt_input() {
true => {},
false => break,
}
} else {
return; //If ready is false, quit the program
}
},
None => {} //Ready is None, so continue waiting
}
}
}
fn connected() -> &mut bool{
println!("Connected to Service! Please enter a command. (hint: help)\n\n");
true
}
fn not_connected() -> &mut bool{
println!("Connection to Service failed :(");
false
}
问题: 你会如何在Rust中解决这个问题?我尝试了将它传递给所有库方法调用,但遇到了一些关于在FnOnce()闭包中借用不可变对象的主要问题。