AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / user-2628868

Dolphin's questions

Martin Hope
Dolphin
Asked: 2025-03-23 15:02:48 +0800 CST

在 Rust 中阻止同步函数中调用异步代码

  • 6

我想在 rust 中调用 http rpc,但当前上下文是同步的。然后我尝试像这样调用远程 rpc:

 let uniq_id = executor::block_on(get_snowflake_id());

这是get_snowflake_id功能:

use std::env;
use log::error;
use reqwest::Client;
use rust_wheel::model::response::api_response::ApiResponse;

pub async fn get_snowflake_id() -> Option<i64> {
    let client = Client::new();
    let infra_url = env::var("INFRA_URL").expect("INFRA_URL must be set");
    let url = format!("{}{}", infra_url, "/infra-inner/util/uniqid/gen");
    let resp = client
        .get(format!("{}", url))
        .body("{}")
        .send()
        .await;
    if let Err(e) = resp {
        error!("get id failed: {}", e);
        return None;
    }
    let text_response = resp.unwrap().text().await;
    if let Err(e) = text_response {
        error!("extract text failed: {}", e);
        return None;
    }
    let resp_str = text_response.unwrap_or_default();
    let resp_result = serde_json::from_str::<ApiResponse<i64>>(&resp_str);
    if let Err(pe) = resp_result {
        error!("parse failed: {}, response: {}", pe, &resp_str);
        return None;
    }
    Some(resp_result.unwrap().result)
}

但此代码被永久阻止,我在同步上下文中调用异步代码的方法是否正确?我必须这样做,因为上下文是同步的,我无法将当前上下文调用样式更改为异步。我试过:

pub fn get_uniq_id() -> Option<i64> {
    task::block_in_place(|| {
        tokio::runtime::Handle::current().block_on(get_snowflake_id())
    })
}

显示错误 can call blocking only when running on the multi-threaded runtime。这是应用程序入口:

#[actix_web::main]
async fn main() -> std::io::Result<()> {}
rust
  • 1 个回答
  • 49 Views
Martin Hope
Dolphin
Asked: 2025-03-23 13:25:06 +0800 CST

特征 `types::_::_serde::Deserialize<'_>` 未针对 `IpNetwork` 实现

  • 5

当我在 rust(1.84.0) 模型中使用时,显示错误:

 the trait `types::_::_serde::Deserialize<'_>` is not implemented for `IpNetwork`

但我确实需要反序列化模型,我无法更改 ipnetwork 代码,我该如何解决这个问题?这是依赖项:

ipnetwork = "0.21.1"

这是我定义的模型:

#![allow(unused)]
#![allow(clippy::all)]

use std::fmt::Display;

use serde::Serialize;
use serde::Deserialize;
use crate::model::diesel::dolphin::dolphin_schema::*;
use bigdecimal::BigDecimal;
use chrono::DateTime;
use chrono::offset::Utc;
use ipnetwork::IpNetwork;
#[derive(Insertable,Queryable,QueryableByName,Debug,Serialize,Deserialize,Default,Clone)]
#[diesel(table_name = users)]
pub struct User {
    pub id: i64,
    pub nickname: String,
    pub avatar_url: String,
    pub phone: String,
    pub updated_time: i64,
    pub created_time: i64,
    pub salt: String,
    pub pwd: String,
    pub sex: i32,
    pub level_type: String,
    pub phone_region: String,
    pub country_code: String,
    pub user_status: i32,
    pub last_login_time: Option<i64>,
    pub first_login_time: Option<i64>,
    pub app_id: String,
    pub register_time: i64,
    pub apple_iap_product_id: Option<String>,
    pub auto_renew_product_expire_time_ms: Option<i64>,
    pub is_guest: i32,
    pub product_id: i32,
    pub register_ip: String,
    pub reg_ip: Option<IpNetwork>,
}
rust
  • 1 个回答
  • 27 Views
Martin Hope
Dolphin
Asked: 2025-02-09 16:20:19 +0800 CST

错误 [ERR_MODULE_NOT_FOUND]:使用捆绑器解析时找不到模块

  • 6

我在我的项目中切换到 bunder 分辨率,项目构建过程运行良好,当运行此应用程序时,显示错误:

 node:internal/errors:496
│     ErrorCaptureStackTrace(err);
│     ^
│
│ Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/home/node/app/dist/websocket/config/setup' imported from /home/node/app/dist/app.js
│     at new NodeError (node:internal/errors:405:5)
│     at finalizeResolution (node:internal/modules/esm/resolve:327:11)
│     at moduleResolve (node:internal/modules/esm/resolve:980:10)
│     at defaultResolve (node:internal/modules/esm/resolve:1206:11)
│     at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:404:12)
│     at ModuleLoader.resolve (node:internal/modules/esm/loader:373:25)
│     at ModuleLoader.getModuleJob (node:internal/modules/esm/loader:250:38)
│     at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:76:39)
│     at link (node:internal/modules/esm/module_job:75:36) {
│   url: 'file:///home/node/app/dist/websocket/config/setup',
│   code: 'ERR_MODULE_NOT_FOUND'
│ }
│
│ Node.js v18.20.6

这是打字稿配置:

{
    "compilerOptions": {
      "target": "ES2020",
      "module": "esnext",
      "moduleResolution": "bundler",
      "outDir": "./dist",
      "rootDir": "./src",
      "strict": true,
      "esModuleInterop": true,
      "skipLibCheck": true,
      "forceConsistentCasingInFileNames": true,
      "declaration": true,
    },
    "include": ["src/**/*"],
    "files": ["src/app.ts"]
  }

bundler 解析不需要添加文件扩展名。为什么会显示这个错误?这是package.json:

{
  "name": "texhub-broadcast",
  "version": "1.0.19",
  "description": "",
  "main": "./dist/app.js",
  "module": "./dist/app.js",
  "types": "./dist/app.d.ts",
  "type":"module",
  "exports": {
    "./dist/websocket/conn/socket_io_client_provider": "./dist/websocket/conn/socket_io_client_provider.js",
    ".": {
      "import": "./dist/app.js"
    }
  },
  "files": [
    "dist/*"
  ],
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "lint": "eslint --fix",
    "dev": "vite-node src/app.ts",
    "build": "npx tsc",
    "dist": "npx tsc"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "dotenv": "^16.4.7",
    "express": "^4.21.2",
    "flatted": "^3.3.2",
    "globals": "^15.14.0",
    "lib0": "^0.2.99",
    "lodash": "^4.17.21",
    "log4js": "^6.9.1",
    "meilisearch": "^0.35.1",
    "prom-client": "^14.2.0",
    "socket.io": "^4.8.1",
    "socket.io-client": "^4.8.1",
    "ws": "^8.18.0",
    "y-leveldb": "^0.1.2",
    "y-protocols": "^1.0.6",
    "y-websocket": "^1.5.0",
    "yjs": "^13.6.23"
  },
  "devDependencies": {
    "@types/express": "^5.0.0",
    "@types/lodash": "^4.17.15",
    "@types/node": "^22.12.0",
    "@types/ws": "^8.5.14",
    "@typescript-eslint/eslint-plugin": "^8.22.0",
    "@typescript-eslint/parser": "^8.22.0",
    "eslint": "^9.19.0",
    "typescript": "^5.7.3",
    "vite": "^6.0.11",
    "vite-node": "^3.0.4",
    "vitest": "^3.0.4"
  }
}

这是导入样式:

import { setupWSConnection } from "./websocket/config/setup";

这是 dist 文件结构:

├── dist
│   ├── websocket
|        |__ config
|              |_ setup.js
│   └── app.js
├── package-lock.json
├── package.json
├── src
│   ├── websoccket
|         |_ config
|               |_ setup.ts  
│   └── app.ts
└── tsconfig.json
node.js
  • 2 个回答
  • 44 Views
Martin Hope
Dolphin
Asked: 2024-12-29 22:28:32 +0800 CST

如何在使用 Spring Boot 应用启动 Junit 测试用例时忽略租户配置

  • 5

当我启动 Spring Boot 应用程序时,我使用此代码将应用程序设置为忽略租户:

CommonContext.setTenantIgnore(true);

这很好用。然后我编写了一个 JUnit 测试用例,我还需要通过使用来忽略租户CommonContext.setIgnoreTenant(true),我曾尝试过这样的方法:

    @BeforeAll
    public static void before() {
        CommonContextHolder.setTenantIgnore(true);
    }

    @BeforeEach
    void init() {
        CommonContextHolder.setTenantIgnore(true);
    }

    @Before
    public void setup() {
        CommonContextHolder.setTenantIgnore(true);
    }

也尝试过这样的:

@SpringJUnitConfig
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class TenantIgnore {
    @BeforeAll
    public static void setUp() {
        CommonContextHolder.setTenantIgnore(true);
    }
}

也不起作用。我应该怎么做才能在启动所有单元测试之前设置租户忽略?我认为它应该在 JUnit 应用程序启动之前(或在 spring 容器启动之前),在所有测试类之前。我也尝试了扩展:

import org.junit.jupiter.api.extension.BeforeAllCallback;
import org.junit.jupiter.api.extension.ExtensionContext;

public class YourExtension implements BeforeAllCallback, ExtensionContext.Store.CloseableResource {

    private static boolean started = false;

    @Override
    public void beforeAll(ExtensionContext context) {
         CommonContextHolder.setTenantIgnore(true);
    }

    @Override
    public void close() {
        
    }
}
java
  • 1 个回答
  • 46 Views
Martin Hope
Dolphin
Asked: 2024-10-02 19:53:42 +0800 CST

如何修复第二个 actix web 服务配置 404 未找到错误

  • 5

我想在使用 actix-web 时限制每个 api 的上传文件大小,因此我像这样调整代码(旧配置仅包含一项服务):

pub fn config(cfg: &mut web::ServiceConfig) {
    cfg.service(
        web::scope("/tex/project")
            .route("/list", web::get().to(get_projects))
            .route("/copy", web::post().to(cp_proj)),
    );
    // https://stackoverflow.com/questions/71714621/actix-web-limit-upload-file-size
    cfg.app_data(
        MultipartFormConfig::default()
            .total_limit(1048576) // 1 MB = 1024 * 1024
            .memory_limit(2097152) // 2 MB = 2 * 1024 * 1024
            .error_handler(handle_multipart_error),
    )
    .service(web::scope("/tex/project").route("/upload", web::post().to(upload_full_proj)));
    cfg.app_data(
        MultipartFormConfig::default()
            .total_limit(104857600) // 100 MB = 1024 * 1024
            .memory_limit(209715200) // 200 MB = 200 * 1024 * 1024
            .error_handler(handle_multipart_error),
    )
    .service(web::scope("/tex/project").route("/file/upload", web::post().to(upload_proj_file)));
}

在我拆分配置后,似乎只有第一个服务配置有效,当我使用第二个 URL 上传时,显示 404 未找到错误。我遗漏了什么吗?我尝试使用不同的名称调整范围,但仍然没有解决这个问题。

pub fn config(cfg: &mut web::ServiceConfig) {
        cfg.service(
            web::scope("/tex/project")
                .route("/list", web::get().to(get_projects))
                .route("/copy", web::post().to(cp_proj)),
        );
        // https://stackoverflow.com/questions/71714621/actix-web-limit-upload-file-size
        cfg.app_data(
            MultipartFormConfig::default()
                .total_limit(1048576) // 1 MB = 1024 * 1024
                .memory_limit(2097152) // 2 MB = 2 * 1024 * 1024
                .error_handler(handle_multipart_error),
        )
        .service(web::scope("/tex/project/proj").route("/upload", web::post().to(upload_full_proj)));
        cfg.app_data(
            MultipartFormConfig::default()
                .total_limit(104857600) // 100 MB = 1024 * 1024
                .memory_limit(209715200) // 200 MB = 200 * 1024 * 1024
                .error_handler(handle_multipart_error),
        )
        .service(web::scope("/tex/project/file").route("/upload", web::post().to(upload_proj_file)));
    }
rust
  • 1 个回答
  • 23 Views
Martin Hope
Dolphin
Asked: 2024-09-22 13:24:02 +0800 CST

如何让 rust actix web 返回直接在浏览器中打开的静态文件

  • 5

我正在使用 actix-web 提供静态 pdf 文件预览,这是 rust 代码:

use actix_web::{error::ErrorBadRequest, web, App, HttpRequest, HttpServer, Responder};
use actix_files::{Files, NamedFile};
use mime::Mime;

async fn namefile(req: HttpRequest) -> impl Responder {
    let pdf_file_path = "/Users/xiaoqiangjiang/source/reddwarf/backend/rust-learn/doc/sample.pdf";
    match NamedFile::open(&pdf_file_path) {
        Ok(file) => {
            let content_type: Mime = "application/pdf".parse().unwrap();
            return NamedFile::set_content_type(file, content_type).into_response(&req);
        }
        Err(e) => {
            return ErrorBadRequest("File not Found").into();
        }
    }
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .route("/namefile", web::get().to(namefile))
            .service(Files::new("/static", "./static").show_files_listing())
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

这是Cargo.toml:

[package]
name = "rust-learn"
version = "0.1.0"
edition = "2018"

[dependencies]
actix-web = "4"
actix-files = "0.6.2"
mime = "0.3.17"

[profile.release]
debug = true

但是当我使用 URL http://localhost:8080/namefile 在 Google Chrome 中访问 pdf 时,它会弹出下载窗口。是否可以在 Google Chrome 浏览器中预览 pdf?不弹出下载窗口。

rust
  • 1 个回答
  • 25 Views
Martin Hope
Dolphin
Asked: 2024-07-23 23:10:08 +0800 CST

具有副作用的接口以某种方式失败,与 `mallctl*()` 读/写处理无直接关系

  • 6

当我尝试在带有 M1 芯片的 macOS 13.4 中转储 Rust 时,如下所示:

use jemalloc_ctl::{AsName, Access};
use std::collections::HashMap;

#[global_allocator]
static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc;

const PROF_ACTIVE: &'static [u8] = b"prof.active\0";
const PROF_DUMP: &'static [u8] = b"prof.dump\0";
const PROFILE_OUTPUT: &'static [u8] = b"profile.out\0";

fn set_prof_active(active: bool) {
    let name = PROF_ACTIVE.name();
    name.write(active).expect("Should succeed to set prof");
}

fn dump_profile() {
    let name = PROF_DUMP.name();
    name.write(PROFILE_OUTPUT).expect("Should succeed to dump profile")
}

fn main() {
    set_prof_active(true);

    let mut buffers: Vec<HashMap<i32, i32>> = Vec::new();
    for _ in 0..100 {
        buffers.push(HashMap::with_capacity(1024));
    }

    set_prof_active(false);
    dump_profile();
}

输出显示以下错误:

thread 'main' panicked at src/main.rs:18:32:
Should succeed to dump profile: An interface with side effects failed in some way not directly related to `mallctl*()` read/write processing.
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

jemolloc 不支持 macOS 吗?我是不是漏掉了什么?这是Cargo.toml:

[package]
name = "rust-learn"
version = "0.1.0"
edition = "2018"

[dependencies]
jemallocator = "0.3.2"
jemalloc-ctl = "0.3.2"

[dependencies.jemalloc-sys]
version = "0.3.2"
features = ["stats", "profiling", "unprefixed_malloc_on_supported_platforms"]

[profile.release]
debug = true

这是 Rust 版本:

➜  rust-learn git:(rustflags) ✗ rustup -V
rustup 1.27.1 (54dd3d00f 2024-04-24)
info: This is the version for the rustup toolchain manager, not the rustc compiler.
info: The currently active `rustc` version is `rustc 1.79.0 (129f3b996 2024-06-10)
rust
  • 1 个回答
  • 29 Views
Martin Hope
Dolphin
Asked: 2024-05-05 11:35:52 +0800 CST

使用 Rust 在 url 中添加空格来打破日期和时间

  • 4

我正在尝试使用 urlencoding 来解码 url 日期时间,如下所示:

fn main() {
    let result = urlencoding::decode("gmt_create=2024-05-05+11%3A14%3A19");
    print!("{}",result.unwrap_or_default().into_owned());
}

url 参数很长。如何使日期和时间与空格连接?不使用 + 。这是Cargo.toml:

[dependencies]
urlencoding = "2.1.3"

我希望这个结果可能看起来像这样:gmt_payment=2024-05-05 00:05:28。我尝试过使用decode_component但在urlencoding中没有找到这个功能。我也尝试过这样的:

use percent_encoding::percent_decode_str;

fn main() {
    let encoded_str = "gmt_create=2024-05-05+11%3A14%3A19";
    let decoded_str = percent_decode_str(encoded_str).decode_utf8().unwrap();
    println!("Decoded string: {}", decoded_str);
}

还是没用。

http
  • 1 个回答
  • 23 Views
Martin Hope
Dolphin
Asked: 2024-01-08 19:25:37 +0800 CST

React setstate 没有触发地图重新渲染

  • 5

我有一个由地图渲染的列表组件,这就是我在反应函数组件中定义数据的方式:

const [projMap, setProjMap] = useState<Map<number, FolderModel>>(new Map<number, FolderModel>());

当我在反应功能组件中设置地图时,如下所示:

React.useEffect(() => {
    if (folderProjList && folderProjList.length > 0) {
        if (currFolder) {
            let cachedExpand = projMap.get(currFolder.id)?.expand;
            let folderModel: FolderModel = {
                expand: cachedExpand ? cachedExpand : true,
                projects: folderProjList
            };
            projMap.set(currFolder.id, folderModel);
            setProjMap(projMap);
        }
    }
}, [folderProjList]);

使用 projMap 渲染 UI 时未触发重新渲染。然后我像这样改变样式:

React.useEffect(() => {
        if (folderProjList && folderProjList.length > 0) {
            if (currFolder) {
                setProjMap((prevMapState) => {
                    const newMapState = new Map<number, FolderModel>(prevMapState);
                    let cachedExpand = newMapState.get(currFolder.id)?.expand;
                    let folderModel: FolderModel = {
                        expand: cachedExpand ? cachedExpand : true,
                        projects: folderProjList
                    };
                    newMapState.set(currFolder.id, folderModel);
                    return newMapState;
                });
            }
        }
    }, [folderProjList]);

重新渲染效果很好。用户界面始终保持最新。这两种setState有什么不同?为什么第二种风格可以立即重新渲染,而第一种风格却不能?

reactjs
  • 2 个回答
  • 44 Views
Martin Hope
Dolphin
Asked: 2024-01-02 19:51:22 +0800 CST

打开 rust 生成的 zip 文件时出现未定义错误 0

  • 5

我正在使用此 rust 代码在 macOS 13.3.1 中生成 zip 文件:

use std::{path::Path, fs::File};
use zip::{ZipWriter, write::FileOptions};

fn main() {
    let file = File::create("/Users/xiaoqiangjiang/source/reddwarf/backend/texhub-server/archive.zip").unwrap();
    let mut zip = ZipWriter::new(file);
    let folder_path = Path::new("/Users/xiaoqiangjiang/source/reddwarf/backend/texhub-server");
    visit_folder(folder_path, &mut zip, "").unwrap();
    zip.finish().unwrap();
}

fn visit_folder(path: &Path, zip: &mut ZipWriter<File>, parent: &str) -> std::io::Result<()> {
    for entry in path.read_dir()? {
        let entry = entry?;
        let file_path = entry.path();
        let file_name = file_path.file_name().unwrap().to_string_lossy().into_owned();
        let zip_path = format!("{}{}/{}", parent, path.file_name().unwrap().to_string_lossy(), file_name);
        if file_path.is_dir() {
            visit_folder(&file_path, zip, &zip_path)?;
        } else {
            let mut file = File::open(&file_path)?;
            let options = FileOptions::default()
                .compression_method(zip::CompressionMethod::Deflated)
                .unix_permissions(0o755);
            zip.start_file(zip_path, options)?;
            std::io::copy(&mut file, zip)?;
        }
    }
    Ok(())
}

这段代码工作正常,但是当我打开 rust 生成的 zip 文件时。显示错误Error 0 - undefined error 0。我错过了什么吗?我应该怎么做才能解决这个问题?这是Cargo.toml:

[package]
name = "rust-learn"
version = "0.1.0"
edition = "2018"

[dependencies]
serde = { version = "1.0.64", features = ["derive"] }
serde_json = "1.0.64"
rust_wheel = { git = "https://github.com/jiangxiaoqiang/rust_wheel.git", branch = "diesel2.0", features = [
    "model",
    "common",
    "rwconfig",
    "texhub"
] }
zip = "0.6"
rust
  • 1 个回答
  • 52 Views
Martin Hope
Dolphin
Asked: 2023-09-25 01:38:22 +0800 CST

如何将 jsonb 数据模型迁移到 Diesel 2.x?

  • 5

jsonb在 Diesel 1.x 中,我定义了一个反映如下数据类型的模型:

use diesel::pg::types::sql_types::Jsonb;

#[derive(FromSqlRow, AsExpression, serde::Serialize, serde::Deserialize, Debug, Default)]
#[sql_type = "Jsonb"]
pub struct ChannelTag {
    pub id: i32,
    pub name: String,
}

今天我将Diesel升级到2.0.4并编译项目时,出现错误:

error[E0603]: module `types` is private
 --> src/model/app/cruise/channel/channel_tag.rs:1:17
  |
1 | use diesel::pg::types::sql_types::Jsonb;
  |                 ^^^^^ private module

看来他们将types模块转为私有,不再对外公开?那么我应该如何定义jsonbDiesel 2.x 中的数据类型呢?

postgresql
  • 1 个回答
  • 25 Views
Martin Hope
Dolphin
Asked: 2023-09-03 23:03:32 +0800 CST

使用 rust serde json 时是否可以尝试转换数据类型

  • 5

我正在使用 rust serde json 反序列化一些 json 字符串,由于某种原因(前端 javascript 无法处理 i64 数据类型,更多信息从这里:Javascript long integer),服务器端默认将 i64 转换为字符串。此默认操作使 rust 反序列化数据失败,这是显示此问题的最小演示:

use serde::{Serialize, Deserialize};

#[tokio::main]
async fn main() {
    let text_response = "{\"id\":\"1\"}";
    let resp_result = serde_json::from_str::<RdUserInfo>(&text_response);
    if let Err(e) = resp_result {
        print!("{}", e);
    }
}

#[derive(Serialize, Deserialize)]
pub struct RdUserInfo {
    pub id: i64,
}

这是Cargo.toml:

[package]
name = "rust-learn"
version = "0.1.0"
edition = "2018"

[dependencies]
serde = { version = "1.0.64", features = ["derive"] }
serde_json = "1.0.64"

我想知道是否可以尝试将字符串转换为 i64,如果失败,则抛出错误。我已经尝试过这样的:

#[derive(Serialize, Deserialize)]
pub struct RdUserInfo {
    #[serde(try_from = "String")]
    pub id: i64,
}

不工作。顺便说一句,错误表明:

invalid type: string "1", expected i64 at line 1 column 9 

                                                                                                    
json
  • 1 个回答
  • 29 Views
Martin Hope
Dolphin
Asked: 2023-09-01 17:35:20 +0800 CST

借用是由于对 `std::sync::Mutex<UnboundedSender<SSEMessage>>` 的解引用强制而发生的

  • 6

我正在使用 tokiotokio = { version = "1.17.0", features = ["full"] } unbounded_channel通道发送一些 sse 消息,因为我需要从不同的位置发送消息,所以我定义了这样的发送消息函数(这是显示错误的最小重现演示):

use std::sync::{Arc, Mutex};
use tokio::{
    sync::mpsc::{UnboundedReceiver, UnboundedSender},
    task,
};

#[tokio::main]
async fn main() {
    let (tx, rx): (UnboundedSender<String>, UnboundedReceiver<String>) =
        tokio::sync::mpsc::unbounded_channel();
    task::spawn_blocking(move || {
        let shared_tx = Arc::new(Mutex::new(tx));
        shared_tx.lock().unwrap().send("l".to_string());
    });
    tx.send("d".to_string());
}

编译器显示错误:

   > cargo build
   Compiling rust-learn v0.1.0 (/Users/xiaoqiangjiang/source/reddwarf/backend/rust-learn)
warning: unused variable: `rx`
 --> src/main.rs:9:14
  |
9 |     let (tx, rx): (UnboundedSender<String>, UnboundedReceiver<String>) =
  |              ^^ help: if this is intentional, prefix it with an underscore: `_rx`
  |
  = note: `#[warn(unused_variables)]` on by default

error[E0382]: borrow of moved value: `tx`
  --> src/main.rs:15:5
   |
9  |     let (tx, rx): (UnboundedSender<String>, UnboundedReceiver<String>) =
   |          -- move occurs because `tx` has type `UnboundedSender<String>`, which does not implement the `Copy` trait
10 |         tokio::sync::mpsc::unbounded_channel();
11 |     task::spawn_blocking(move || {
   |                          ------- value moved into closure here
12 |         let shared_tx = Arc::new(Mutex::new(tx));
   |                                             -- variable moved due to use in closure
...
15 |     tx.send("d".to_string());
   |     ^^^^^^^^^^^^^^^^^^^^^^^^ value borrowed here after move

For more information about this error, try `rustc --explain E0382`.
warning: `rust-learn` (bin "rust-learn") generated 1 warning
error: could not compile `rust-learn` due to previous error; 1 warning emitted

我已经尝试添加.as_ref()但shared_tx仍然没有解决这个问题。我应该怎么做才能解决这个问题?这是cargo.toml:

[package]
name = "rust-learn"
version = "0.1.0"
edition = "2018"

[dependencies]
tokio = { version = "1.17.0", features = ["full"] }
serde = { version = "1.0.64", features = ["derive"] }
serde_json = "1.0.64"
rust
  • 1 个回答
  • 20 Views
Martin Hope
Dolphin
Asked: 2023-08-27 20:52:43 +0800 CST

`impl Trait` 的不同使用导致 Rust 中不同的不透明类型

  • 5

我定义了两个函数来装箱 actix_web 响应,如下所示:

pub fn box_actix_rest_response<T>(data: T) -> impl Responder where T: Serialize + Default{
    let res = ApiResponse {
        result: data,
        ..Default::default()
    };
    HttpResponse::Ok().json(res)
}

pub fn box_error_actix_rest_response <T>(data: T, result_code: String, msg: String) -> impl Responder where T: Serialize + Default {
    let res = ApiResponse {
        result: data,
        statusCode: "200".to_string(),
        resultCode: result_code,
        msg
    };
    HttpResponse::Ok().json(res)
}

一个函数包装正常响应,另一个包装错误响应,但是当我在同一外层函数中使用这两个函数时,如下所示:

pub fn create_file(add_req: &TexFileAddReq, login_user_info: &LoginUserInfo) -> impl Responder {
    let new_file = TexFileAdd::gen_tex_file(add_req, login_user_info);
    use crate::model::diesel::tex::tex_schema::tex_file as cv_work_table;
    use crate::model::diesel::tex::tex_schema::tex_file::dsl::*;
    let mut query = cv_work_table::table.into_boxed::<diesel::pg::Pg>();
    query = query.filter(
        cv_work_table::parent
            .eq(add_req.parent.clone())
            .and(cv_work_table::name.eq(add_req.name.clone()))
            .and(cv_work_table::file_type.eq(add_req.file_type.clone())),
    );
    let cvs = query.load::<TexFile>(&mut get_connection()).unwrap();
    if !cvs.is_empty() {
        return box_error_actix_rest_response("already exists", "ALREADY_EXISTS".to_owned(), "file/folder already exists".to_owned());
    }
    let result = diesel::insert_into(tex_file)
        .values(&new_file)
        .get_result::<TexFile>(&mut get_connection())
        .expect("failed to add new tex file or folder");
    let resp = box_actix_rest_response(result);
    return resp;
}

显示错误:

mismatched types
expected opaque type `impl Responder` (opaque type at </Users/xiaoqiangjiang/.cargo/git/checkouts/rust_wheel-8476ff1b418e67f8/252bdd6/src/common/wrapper/actix_http_resp.rs:23:88>)
   found opaque type `impl Responder` (opaque type at </Users/xiaoqiangjiang/.cargo/git/checkouts/rust_wheel-8476ff1b418e67f8/252bdd6/src/common/wrapper/actix_http_resp.rs:15:47>)
distinct uses of `impl Trait` result in different opaque typesrustcClick for full compiler diagnostic
actix_http_resp.rs(23, 88): the expected opaque type
actix_http_resp.rs(15, 47): the found opaque type
file_service.rs(106, 81): expected `impl Responder` because of return type

看起来两个函数返回不同Responder,我应该怎么做才能解决这个问题?可以这样使用这两个函数吗?

rust
  • 1 个回答
  • 30 Views
Martin Hope
Dolphin
Asked: 2023-08-27 16:26:35 +0800 CST

未捕获的语法错误:请求的模块“/node_modules/.vite/deps/bootstrap.js”不提供名为“default”的导出

  • 5

当我像这样在 React 项目中导入引导程序时:

import bootstrap from "bootstrap";

显示错误:

Uncaught SyntaxError: The requested module '/node_modules/.vite/deps/bootstrap.js?t=1693123714754&v=6a448f48' does not provide an export named 'default'

这是演示代码:

import React from 'react';
import bootstrap from "bootstrap";

const App: React.FC = () => {

  React.useEffect(() => {
    let modal = document.getElementById('exampleModal');
    if (modal) {
      var myModal = new bootstrap.Modal(modal);
      myModal.show();
    }
  }, []);

  return (
    <div>
      <div className="modal fade" id="exampleModal" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div className="modal-dialog">
          <div className="modal-content">
            <div className="modal-header">
              <h5 className="modal-title" id="exampleModalLabel">Modal title</h5>
              <button type="button" className="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div className="modal-body">
              ...
            </div>
            <div className="modal-footer">
              <button type="button" className="btn btn-secondary" data-bs-dismiss="modal">Close</button>
              <button type="button" className="btn btn-primary">Save changes</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

export default App;

我错过了什么吗?我正在使用此命令来安装引导程序:

pnpm install bootstrap@v5.3.1
reactjs
  • 2 个回答
  • 17 Views
Martin Hope
Dolphin
Asked: 2023-08-21 22:14:03 +0800 CST

目前该平台无法提供创建时间

  • 4

我正在使用此代码来获取 rust 中的最新目录名称(这是展示我如何在项目中使用此代码 snippnet 的最小演示):

use std::fs;

fn main() {
    let subdirectories = fs::read_dir("/opt")
        .unwrap()
        .filter_map(Result::ok)
        .filter(|entry| entry.file_type().unwrap().is_dir())
        .map(|entry| entry.path())
        .collect::<Vec<_>>();
    let latest_directory = subdirectories
        .iter()
        .max_by_key(|&dir| dir.metadata().unwrap().created().unwrap());

    match latest_directory {
        Some(directory) => {
            let name = directory.file_name().unwrap_or_default().to_str().unwrap();
            print!("{}", name);
        }
        None => {
            
        }
    }
}

这在我的本地 macOS 上运行良好,当我部署此代码以在 docker 中与 alpine 一起运行时,显示错误:

thread 'actix-rt|system:0|arbiter:0' panicked at 'called `Result::unwrap()` on an `Err` value: Error { kind: Unsupported, message: "creation time is not available on this platform currently" }', src/service/project/project_service.rs:201:62

我错过了什么吗?这段代码可以在docker环境下运行吗?

rust
  • 1 个回答
  • 44 Views

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    重新格式化数字,在固定位置插入分隔符

    • 6 个回答
  • Marko Smith

    为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会?

    • 2 个回答
  • Marko Smith

    VScode 自动卸载扩展的问题(Material 主题)

    • 2 个回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Martin Hope
    Fantastic Mr Fox msvc std::vector 实现中仅不接受可复制类型 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant 使用 chrono 查找下一个工作日 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor 构造函数的成员初始化程序可以包含另一个成员的初始化吗? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský 为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul C++20 是否进行了更改,允许从已知绑定数组“type(&)[N]”转换为未知绑定数组“type(&)[]”? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann 为什么 {2,3,10} 和 {x,3,10} (x=2) 的顺序不同? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve