小编caf*_*e25的帖子

Rust 中返回函数的正确语法是什么?

Rust 中返回函数的正确语法是什么?

以下代码无法编译。

  fn identity<T>(a: T) -> T {
    return a;
  };

  fn right<T>(a: T) -> Fn {
    return identity;
  };
Run Code Online (Sandbox Code Playgroud)

return function rust

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

Linux下如何使用sendmail命令发送邮件

我尝试了以下两个命令。

  1. From: mail_id
    To: Recipient_mail_id
    Hi, this is my message, and I'm sending it to you!
    .
    
    Run Code Online (Sandbox Code Playgroud)
  2. From: mail_id
    To: Recipient_mail_id
    Hi, this is my message, and I'm sending it to you!
    .
    
    Run Code Online (Sandbox Code Playgroud)

但没有收到任何邮件到收件人的邮件地址。

SMTP 服务器安装在另一台服务器上并且已启动并正在运行。那么任何人都可以帮助我了解如何使用 sendmail 或 smtp 命令通过 SMTP 服务器发送测试电子邮件吗?

linux email sendmail

13
推荐指数
2
解决办法
7万
查看次数

当模板参数全部被推导时,它们的顺序是否重要?

我发现 Clang、GCC 和 MSVC 之间存在差异,其中 GCC 和 Clang 执行了我所期望的操作:

#include <Eigen/Core>

template <typename Indices, typename T, int Rows> //< Bad
//template <typename Indices, int Rows, typename T> //< OK
//template <typename T, int Rows, typename Indices> //< OK
//template <typename T, typename Indices, int Rows> //< Bad
//template <int Rows, typename Indices, typename T> //< Bad
//template <int Rows, typename T, typename Indices> //< Bad
void f(
    const Eigen::Matrix<T, Rows, 1>&,
    const Indices&
) {}


int main() {
    f(Eigen::Matrix<double, 6, …
Run Code Online (Sandbox Code Playgroud)

c++ language-lawyer template-argument-deduction

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

寻找 C memcpy 等效项

将字节从 src 写入 dst 的最有效(不安全)方法

我发现copy_nonoverlapping

pub unsafe fn copy_nonoverlapping(src: *const T, dst: *mut T, count: usize)
将 count * size_of::() 个字节从 src 复制到 dst。源和目的地不得重叠

我要写入的数据位于bufat index 4,我想将其写入_bytes_buffat (variable) index index * MAX_DATA_LENGTHMAX_DATA_LENGTH约为64Kb。

不过,我在让它发挥作用时遇到了一些麻烦。请参阅以下我当前尝试正确编写它的片段:

let mut  _bytes_buf:Vec<u8>; // big buffer, we don't know the total size at compilation
let mut buf = [0u8; MAX_DATA_LENGTH]; // small buffer

// [...] we now know the size, I write '3' below to make it …
Run Code Online (Sandbox Code Playgroud)

rust

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

tokio可以理解为类似于Javascript的事件循环或者像它一样使用吗?

我不确定它是否tokio类似于 Javascript 中的事件循环,也是一个非阻塞运行时,或者它是否可以用于以类似的方式工作。以我的理解,tokio是 Rust 中 future 的运行时。因此,它必须实现某种用户态线程或任务,这可以通过事件循环(至少部分)来调度新任务来实现。

我们来看下面的 Javascript 代码:

console.log('hello1');
setTimeout(() => console.log('hello2'), 0);
console.log('hello3');
setTimeout(() => console.log('hello4'), 0);
console.log('hello5');
Run Code Online (Sandbox Code Playgroud)

输出将是

hello1
hello3
hello5
hello2
hello4
Run Code Online (Sandbox Code Playgroud)

我怎样才能在东京做到这一点?tokio 总体上是这样工作的吗?我尝试了以下代码

async fn set_timeout(f: impl Fn(), ms: u64) {
    tokio::time::sleep(tokio::time::Duration::from_millis(ms)).await;
    f()
}

#[tokio::main]
async fn main() {
    println!("hello1");
    tokio::spawn(async {set_timeout(|| println!("hello2"), 0)}).await;
    println!("hello3");
    tokio::spawn(async {set_timeout(|| println!("hello4"), 0)}).await;
    println!("hello5");
}
Run Code Online (Sandbox Code Playgroud)

输出只是

hello1
hello3
hello5
Run Code Online (Sandbox Code Playgroud)

如果我将代码更改为

    println!("hello1");
    tokio::spawn(async {set_timeout(|| println!("hello2"), 0)}.await).await;
    println!("hello3");
    tokio::spawn(async {set_timeout(|| println!("hello4"), 0)}.await).await;
    println!("hello5");
Run Code Online (Sandbox Code Playgroud)

输出是

hello1
hello2 …
Run Code Online (Sandbox Code Playgroud)

rust async-await rust-tokio

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

在 rust/axum 中带或不带尾部斜线的路由路径

我想将http://0.0.0.0/foo和路由http://0.0.0.0/foo/到同一个get_foo处理程序。然而,实际上,只有/foo路由和/foo/404。我怀疑我设置/附加的中间件错误:

use axum::http::StatusCode;
use axum::{routing::{get}, Router};
use std::{net::SocketAddr};
use tower_http::normalize_path::NormalizePathLayer;

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/foo", get(get_foo))
        .layer(NormalizePathLayer::trim_trailing_slash());

    let port_str = std::env::var("PORT").unwrap_or("8000".to_owned());
    let port = port_str.parse::<u16>().unwrap();
    let addr = SocketAddr::from(([0, 0, 0, 0], port));
    println!("listening on http://{}", addr);
    axum::Server::bind(&addr)
        .serve(app.into_make_service())
        .await
        .unwrap();
}

async fn get_foo() -> Result<String, StatusCode>  {
    Ok("Hello from foo.".to_owned())
}

Run Code Online (Sandbox Code Playgroud)

...以及随附的Cargo.toml

[package]
name = "axum_trailing_slash"
version = "0.1.0"
edition = …
Run Code Online (Sandbox Code Playgroud)

rust rust-axum

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

reqwest 作为客户端和 axum 作为服务器的问题(axum 在 1k req/s 时爆炸,端口使用错误)

我有问题,为什么发送时出现此错误request

\n
Error: reqwest::Error {\n    kind: Request, \n    url: Url { \n        scheme: "http", \n        cannot_be_a_base: false, \n        username: "", \n        password: None, \n        host: Some(Ipv4(127.0.0.1)), \n        port: Some(3000), \n        path: "/message", \n        query: None, \n        fragment: None \n    }, \n    source: hyper::Error(\n        Connect, \n        ConnectError(\n            "tcp connect error", \n            Os { \n                code: 10048, \n                kind: AddrInUse, \n                message: "Only one usage of each socket address (protocol/network address/port) is normally permitted." \n            }\n        )\n    )\n}\n
Run Code Online (Sandbox Code Playgroud)\n

它以“随机”速率发生,例如 15-45 …

http rust rust-axum

6
推荐指数
0
解决办法
786
查看次数

告诉编译器泛型返回类型不借用任何对参数的引用?

tldr;> 给定一个接受通用回调参数并返回关联类型的特征函数,编译器会抱怨关联类型可能从回调函数借用参数。有没有办法告诉编译器事实并非如此?

详细信息:我计划实现一个接受回调参数的特征函数,并希望强制该特征函数的实现实际调用该回调。我通过让回调返回一个只能通过调用此回调来构造的类型,并强制特征函数返回该类型来实现此目的。

/// If this type is used as a generic argument in a trait function and that trait function
/// returns `CallbackResult`, then that enforces that any implementation of that
/// trait function must call the callback.
pub trait Callback<T> {
    type CallbackResult;

    fn call(self, v: T) -> Self::CallbackResult;
}
Run Code Online (Sandbox Code Playgroud)

有关如何使用它的示例:

trait MyTrait {
  fn func<C>(&self, callback: C) -> C::CallbackResult
  where
    C: Callback<i32>;
}

struct MyStruct {}
impl MyTrait for MyStruct {
  fn func<C>(&self, callback: C) -> C::CallbackResult …
Run Code Online (Sandbox Code Playgroud)

reference callback rust borrow-checker

6
推荐指数
0
解决办法
88
查看次数

如何迭代大型输入文件?

我正在尝试访问通过输入字段上传的文件内容的迭代器。

我可以通过 web-sys 将 JS 文件传递​​到 Wasm 中,但我一生都无法弄清楚如何访问 Rust 中传递的文件的长度和名称之外的任何内容。

我想我可以将整个文件作为 ByteArray 传递到 Wasm 中并对其进行迭代,但最好我想直接迭代文件内容而不进行复制,因为文件本身会很大(~1 GB)。

我在 Mozilla JS 文档中发现,我应该能够访问底层文件 blob,通过该.stream()方法从中获取 ReadableStream,并从中获取应该能够迭代的 Reader。但在 web-sys 中,.getReader()ReadableStream 的方法返回一个简单的 JSValue,我无法用它做任何有用的事情。

我是否在这里遗漏了一些东西,或者这个功能只是在网络系统中丢失了,还是有其他方法可以做到这一点?也许在 JS 中创建迭代器并将其传递给 Rust?

rust webassembly wasm-bindgen

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

找不到 Rust 编译器来安装 Transformer

我不知道如何修复此错误(对于 Windows 上的 pip install Transformer):\n错误:找不到 Rust 编译器

\n
If you are using an outdated pip version, it is possible a prebuilt wheel is available for this package but pip is not able to install from it. Installing from the wheel would avoid the need for a Rust compiler.\n\nTo update pip, run:\n\n  pip install --upgrade pip\n\nand then retry package installation.\n\nIf you did intend to build this package from source, try installing a Rust compiler from your system package manager and …
Run Code Online (Sandbox Code Playgroud)

windows rust

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