让我们考虑以下示例:
主文件
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) 引入int uncaught_exceptions() noexcept;
inC++17
而不是bool uncaught_exception() noexcept;
引发了一个问题:是否可以同时出现多个异常。
返回值
- 当前线程中未捕获的异常对象的数量。
我试着想象这样一种情况,当它不止一个时。
绞尽脑汁后,我只想到了一个想法:在同一个块内的局部变量throw
中放置一些东西。destructor
try
但还是不行。
首先,它违反了强加于 s 的规则,destructor
迫使他们这样做noexcept
。其次,它可以通过 纠正noexcept(false)
,但它只会跟注terminate
而不是在区块中结束catch
。
所以它并不能解决问题。
最后,在catch
方块内扔任何东西都是很常见的,没有什么不寻常的。因为一旦进入该catch
块,uncaught_exceptions()
就会递减并变为零。
所以我想知道是否有可能想象出这样一种情况,其中uncaught_exceptions()
返回的值会超过1
?
我想知道一些例子,其中将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)
该代码是可编译的,尽管它MyStruct
从main
到func
等移动。
至于Box
和Pin
它们都将其内容保留在堆上,因此它似乎不受动议的影响。
因此,如果有人就这些问题详细阐述这个主题,我将不胜感激。由于其他问题和文档中没有涵盖它,因此仅仅使用Box
.
我想了解以下代码中复制构造函数的双重调用的原因:
#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) 如何在完全不需要加载共享库的情况下编译 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
静态编译?以及如何摆脱链接所有其他共享库?
问题是关于默认情况。
让我们考虑以下代码:
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 程序制作一个 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 …
我想知道如何更改内部的值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)
当突变已经完成并且指针被丢弃时,这会导致恐慌。如何解决呢?
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::Error
以fmt::Error
符合返回的fmt::Result
特征。
我偶然发现了一个在文档中有效的示例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)