我有个问题。我通常使用 Kotlin、Rust 和 Elm 等语言编写代码。这些语言有一个特性,它使我能够从 if 或 switch 表达式中生成一个值,如下所示:
Rust 中的示例:
let x = 10
let biggerThanFive =
if x > 5 {
true
} else {
false
}
Run Code Online (Sandbox Code Playgroud)
Kotlin 中的示例:
val x = 10
val biggerThanFive =
if (x > 5) {
true
} else {
false
}
Run Code Online (Sandbox Code Playgroud)
现在在 Javascript 中,我很少偶然发现使用 if 作为表达式的代码(我通常在匿名函数和箭头函数的帮助下使用它)
const x = 10
const biggerThanFive = (() => {
if(x > 5) {
return true
}
else {
return false
}
})()
Run Code Online (Sandbox Code Playgroud)
相反,它通常是这样做的
const x …Run Code Online (Sandbox Code Playgroud) 我无法理解如何在互斥锁中修改 Option。
当没有选项时,它工作正常
let mut my_int = Arc::new(Mutex::new(5));
let my_int_clone = Arc::clone(&my_int);
thread::spawn(move || {
let mut my_int = my_int_clone.lock().unwrap();
*my_int += 1;
}).join();
let my_int_clone_print = Arc::clone(&my_int);
println!("Value: {}", my_int_clone_print.lock().unwrap());
Run Code Online (Sandbox Code Playgroud)
但是,当我将值包装在 中时Some,我必须手动使用ref mut等(我从这里找到它),因为lock().unwrap()返回的是MutexGuard,而不是Option本身。
let mut my_int = Arc::new(Mutex::new(Some(5)));
let my_int_clone = Arc::clone(&my_int);
thread::spawn(move || {
let mut my_int = my_int_clone.lock().unwrap();
match *my_int {
Some(ref mut val) => {
*val += 1;
},
None => {
println!("Value is …Run Code Online (Sandbox Code Playgroud)