【发布时间】:2015-04-08 17:01:52
【问题描述】:
前言:我已经完成了我的研究,并且知道这确实不是一个好主意/拥有一个 Rust 也不是惯用的。完全愿意接受其他解决此问题的方法的建议。
背景:我有一个连接到 websocket 的控制台应用程序,一旦连接成功,服务器就会发送“已连接”消息。我有发送者,接收者是单独的线程,一切都很好。在connect() 调用之后,一个循环开始并在终端中放置一个提示,表明应用程序已准备好接收来自用户的输入。
问题:问题是当前执行流程调用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() 闭包中借用不可变对象的主要问题。
【问题讨论】:
-
虽然我鼓励您不使用全局可变状态,但如果我没有至少指向 this answer 向您展示如何做到这一点。
标签: global-variables rust