小编dro*_*te7的帖子

`|_| 和有什么不一样 异步移动{}`和`异步移动|_| {}`

让我们考虑以下示例:

主文件

use futures::executor::block_on;
use futures::future::{FutureExt, TryFutureExt};


async fn fut1() -> Result<String, u32> {
  Ok("ok".to_string())
}

fn main() {
    println!("Hello, world!");
    match block_on(fut1().and_then(|x| async move { Ok(format!("{} is \"ok\"", x)) })) {
      Ok(s) => println!("{}", s),
      Err(u) => println!("{}", u)
    };
}

Run Code Online (Sandbox Code Playgroud)

Cargo.toml

[dependencies]
futures = "^0.3"
Run Code Online (Sandbox Code Playgroud)

我问的是表达式|x| async move {}而不是async move |x| {}. 后者更明显,但遇到编译错误:

error[E0658]: async closures are unstable
Run Code Online (Sandbox Code Playgroud)

然后我想知道,async move || {}和之间有什么区别|| async move {}。它们似乎都是使用move关键字的闭包。

$ rustc --version …
Run Code Online (Sandbox Code Playgroud)

rust

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

未捕获的异常数量可以多于一个吗?

引入int uncaught_exceptions() noexcept;inC++17而不是bool uncaught_exception() noexcept;引发了一个问题:是否可以同时出现多个异常。

根据en.cppreference.com

返回值

  1. 当前线程中未捕获的异常对象的数量。

我试着想象这样一种情况,当它不止一个时。

绞尽脑汁后,我只想到了一个想法:在同一个块内的局部变量throw中放置一些东西。destructortry

但还是不行。

首先,它违反了强加于 s 的规则,destructor迫使他们这样做noexcept。其次,它可以通过 纠正noexcept(false),但它只会跟注terminate而不是在区块中结束catch

所以它并不能解决问题。

最后,在catch方块内扔任何东西都是很常见的,没有什么不寻常的。因为一旦进入该catch块,uncaught_exceptions()就会递减并变为零。

所以我想知道是否有可能想象出这样一种情况,其中uncaught_exceptions()返回的值会超过1

c++ exception c++17

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

Pin 与 Box:为什么 Box 还不够?

我想知道一些例子,其中将T类型保留在其中Box是不安全的,而保留在其中Pin则是安全的。

最初,我认为这std::marker::PhantomPinned可以防止实例被移动(通过禁止它),但似乎事实并非如此。自从:

use std::pin::Pin;
use std::marker::PhantomPinned;

#[derive(Debug)]
struct MyStruct {
    field: u32,
    _pin: PhantomPinned
}

impl MyStruct {
    fn new(field: u32) -> Self {
        Self {
            field,
            _pin: PhantomPinned,
        }
    }
}

fn func(x: MyStruct) {
    println!("{:?}", x);
    func2(x);
}

fn func2(x: MyStruct) {
    println!("{:?}", x);
}

fn main() {
    let x = MyStruct::new(5);
    func(x);
}
Run Code Online (Sandbox Code Playgroud)

该代码是可编译的,尽管它MyStructmainfunc等移动。

至于BoxPin它们都将其内容保留在堆上,因此它似乎不受动议的影响。

因此,如果有人就这些问题详细阐述这个主题,我将不胜感激。由于其他问题和文档中没有涵盖它,因此仅仅使用Box.

rust

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

传递给 std::vector::emplace_back 的类的复制构造函数的双重调用

我想了解以下代码中复制构造函数的双重调用的原因:

#include <vector>
#include <thread>
#include <algorithm>
#include <functional>
#include <iostream>
#include <mutex>

std::mutex m_stdout;

class MyWorker {
public:
  MyWorker() = default;
  MyWorker(const MyWorker& mw) {
    m_stdout.lock();
    std::cout << "MyWorker coping" << std::endl;
    m_stdout.unlock();
  }

  void operator() () {}
};

int main () {
  std::vector<std::thread> vth;
  vth.reserve(4);
  MyWorker mw;
  for (int i = 4; i > 0; --i) {
    vth.emplace_back(mw);
  }
  std::for_each(vth.begin(), vth.end(), std::mem_fn(&std::thread::join));
}
Run Code Online (Sandbox Code Playgroud)

标准输出:

MyWorker coping
MyWorker coping
MyWorker coping
MyWorker coping
MyWorker coping
MyWorker coping
MyWorker coping …
Run Code Online (Sandbox Code Playgroud)

c++ c++11

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

如何构建一个没有共享库的 Rust 应用程序?

如何在完全不需要加载共享库的情况下编译 Rust 应用程序?

我试过什么:

前任

fn main() {
  println!("Try to compile me statically!");
}
Run Code Online (Sandbox Code Playgroud)

根据https://rust-lang.github.io/rfcs/1721-crt-static.html我执行了以下操作:

fn main() {
  println!("Try to compile me statically!");
}
Run Code Online (Sandbox Code Playgroud)

为什么不libc静态编译?以及如何摆脱链接所有其他共享库?

static-linking rust

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

在模式匹配的默认情况下,如何访问匹配值?

问题是关于默认情况。

让我们考虑以下代码:

fn func(x: i64) {
  match x {
    0 => println!("Zero"),
    1 => println!("One"),
    _ => {
      //How to get the value here not via repeating the matched expression ?
    }
  };
}
Run Code Online (Sandbox Code Playgroud)

rust

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

docker 中的 Rust actix_web 无法实现,为什么?

我正在尝试为我的 rust 程序制作一个 docker 容器,让我们看看

文件

FROM debian

RUN apt-get update && \
    apt-get -y upgrade && \
    apt-get -y install git curl g++ build-essential

RUN curl https://sh.rustup.rs -sSf | bash -s -- -y

WORKDIR /usr/src/app

RUN git clone https://github.com/unegare/rust-actix-rest.git

RUN ["/bin/bash", "-c", "source $HOME/.cargo/env; cd ./rust-actix-rest/; cargo build --release; mkdir uploaded"]

EXPOSE 8080

ENTRYPOINT ["/bin/bash", "-c", "echo 'Hello there!'; source $HOME/.cargo/env; cd ./rust-actix-rest/; cargo run --release"]

Run Code Online (Sandbox Code Playgroud)

cmd运行: docker run -it -p 8080:8080 rust_rest_api/dev

但从外部卷曲curl -i -X POST -F …

rust docker rust-actix

4
推荐指数
2
解决办法
1217
查看次数

Rust Arc 如何 get_mut 并在之后恢复 Arc 的其他副本读取的能力?

我想知道如何更改内部的值Arc,然后再次制作有效的其他副本Arc

use std::sync::Arc;
use std::thread;
use std::error::Error;
use std::io;
use std::time::Duration;

#[derive(Debug)]
struct El {
  n: i64,
}

fn main() -> io::Result<()> {
  let mut a = Arc::new(El{n: 5});
  let b = Arc::clone(&a);
  let th = thread::spawn(move || {
    println!(r#"Hello, World!"#);
    thread::sleep(Duration::from_millis(1000));
    println!("{:?}", b);
  });
  let mut c = Arc::get_mut(&mut a).unwrap();
  c.n = 10;
  drop(c);
  drop(a);
  th.join().expect("some errors occured");
  Ok(())
}
Run Code Online (Sandbox Code Playgroud)

当突变已经完成并且指针被丢弃时,这会导致恐慌。如何解决呢?

rust

4
推荐指数
2
解决办法
1万
查看次数

实施 fmt::Display 时应如何处理错误?

fmt::Error我想知道如何将, 轨道上可能出现的其他类型的临时错误正确转换fn fmt为该fmt::Error类型?

比方说:

use std::fmt;
use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize)]
struct MyStruct {
    x: i32
}

impl fmt::Display for MyStruct {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", serde_json::to_string(&self).map_err(|e| /*???*/)?)
    }
}
Run Code Online (Sandbox Code Playgroud)

如上面的示例所示,我想知道我应该如何转换,例如,serde_json::Errorfmt::Error符合返回的fmt::Result特征。

error-handling rust

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

以“static”为前缀的闭包是什么意思?我什么时候会使用它?

我偶然发现了一个在文档中有效的示例static || { }。然而,在我自己的代码中使用这样的表达式的尝试失败了。我想知道为什么。

来自https://doc.rust-lang.org/stable/std/pin/macro.pin.html的例子

#![feature(generators, generator_trait)]
use std::{
    ops::{Generator, GeneratorState},
    pin::pin,
};

fn generator_fn() -> impl Generator<Yield = usize, Return = ()> /* not Unpin */ {
 // Allow generator to be self-referential (not `Unpin`)
 // vvvvvv        so that locals can cross yield points.
    static || {
        let foo = String::from("foo");
        let foo_ref = &foo; // ------+
        yield 0;                  // | <- crosses yield point!
        println!("{foo_ref}"); // <--+
        yield foo.len();
    }
}

fn main() {
    let …
Run Code Online (Sandbox Code Playgroud)

static closures rust

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