小编Val*_*ani的帖子

在 Javascript 中执行“函数式”if-as-expression 是个好主意吗?

我有个问题。我通常使用 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)

javascript expression if-statement

1
推荐指数
1
解决办法
60
查看次数

Rust 从互斥锁访问选项

我无法理解如何在互斥锁中修改 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)

concurrency mutex rust

0
推荐指数
1
解决办法
1270
查看次数

标签 统计

concurrency ×1

expression ×1

if-statement ×1

javascript ×1

mutex ×1

rust ×1