小编caf*_*e25的帖子

在当前作用域中未找到单元类型“()”名为“save”的方法

我想合并两个图像。我正在使用image::imageops::overlay图像箱中的:

use image::imageops::overlay;
use std::path::Path;

fn main() {
    let path1 = Path::new("~/Desktop/to-merge/image1.png");
    let path2 = Path::new("~/Desktop/to-merge/image2.png");
    let mut img1 = image::open(&path1).unwrap().clone();
    let mut img2 = image::open(&path2).unwrap().clone();
    let output = overlay(&mut img1, &mut img2, 0, 0);
    let save_path = Path::new("~/Desktop/to-crop/merged.png");
    output.save(save_path).unwrap();
}
Run Code Online (Sandbox Code Playgroud)

点击后cargo run,我收到此错误:

use image::imageops::overlay;
use std::path::Path;

fn main() {
    let path1 = Path::new("~/Desktop/to-merge/image1.png");
    let path2 = Path::new("~/Desktop/to-merge/image2.png");
    let mut img1 = image::open(&path1).unwrap().clone();
    let mut img2 = image::open(&path2).unwrap().clone();
    let output = overlay(&mut img1, &mut img2, 0, …
Run Code Online (Sandbox Code Playgroud)

rust

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

收集元素时设置向量的容量

我正在开发一个项目,我需要重复地将已知数量的元素从缓冲区收集到向量中,我当前的代码是:

let mut info: Vec<i32> = buffer.trim().split(" ").collect()
Run Code Online (Sandbox Code Playgroud)

然而,据我所知,我将收到 2 个元素,我希望能够设置向量的容量,例如:

let mut info: Vec<i32>::with_capacity(2) = buffer.trim().split(" ").collect()
Run Code Online (Sandbox Code Playgroud)

iterator collect rust

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

关于 Rust 中的 Boxed Future 的编译器错误消息有点令人困惑

我似乎不明白这里的编译器错误消息。对于以下代码片段

use std::pin::Pin;
use std::future::Future;

fn give_future<'a>(x : &'a i32) -> Pin<impl Future<Output=&'a i32> + 'a> {
    Box::pin(async move { x })
}
Run Code Online (Sandbox Code Playgroud)

它说以下内容

error[E0277]: `[async block@src/lib.rs]` cannot be unpinned
 --> src/lib.rs:7:47
  |
  | fn give_future<'a>(x : &'a i32) -> Pin<impl Future<Output=&'a i32> + 'a> {
  |                                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Unpin` is not implemented for `[async block@src/lib.rs]`
  |
  = note: consider using the `pin!` macro
          consider using `Box::pin` if you need to access the pinned value outside of the current …
Run Code Online (Sandbox Code Playgroud)

future rust

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

函数接受泛型类型 T 的迭代器,并返回仅给出点特定半径内的 T 的迭代器

我想编写一个函数,它接受泛型类型的迭代器T,并返回一个仅给出T点特定半径内的迭代器。因为特征不能包含关联字段,并且我不想为 every实现GetXand ,所以我还将传入一个函数来检索every 的and位置。GetYTxyT

我意识到这不是最有效的空间分区/宽相碰撞检测算法,但我只是想向自己证明具有此签名的函数可以存在于借用检查规则中。

如果这个函数签名无法实现,我该如何修改它以使其工作,并且对T和 的约束/界限最少impl Iterator

这是我的尝试:

pub fn filter<'a, T>(
    world: impl Iterator<Item = &'a T>,
    positions: fn(&'a T) -> (f32, f32),
    near_to: (f32, f32),
    radius: f32,
) -> impl Iterator<Item = &'a T> {
    //We cannot access a field of the geneic item "T" directly, so we instead pass a function that retrieves that field from each "T".
    let positions = …
Run Code Online (Sandbox Code Playgroud)

rust

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

预期为“&amp;Arc&lt;ProxyPool&gt;”,找到“&amp;ProxyPool”

我尝试从&ProxyPoolto克隆引用&Arc<ProxyPool>,但仍然收到错误,引用的类型仍然是&ProxyPool

pub struct ProxyPool {
    connections: Mutex<Vec<TcpStream>>,
    proxy_addresses: Arc<Vec<SocketAddr>>,
}
pub struct PooledConnection {
    stream: TcpStream,
    pool: Arc<ProxyPool>,
}

impl ProxyPool {
    async fn get_connection(&self) -> Result<PooledConnection> {
        loop {
            if let Some(conn) = {
                let mut connections = self.connections.lock().unwrap();
                connections.pop()
            } {
                return Ok(PooledConnection {
                    stream: conn,
                    pool: Arc::clone(self), // converting &ProxyPool to Arc<ProxyPool>
                });
            }
            // If no connection is available, wait a bit and try again.
            tokio::time::sleep(Duration::from_millis(100)).await;
        }
    }

    fn return_connection(&self, …
Run Code Online (Sandbox Code Playgroud)

proxy networking reference rust

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

当尝试运行 C 程序的多个实例时,Ctrl + C 不起作用

我正在阅读一本有关操作系统的开源教科书,这是第一个代码示例(文件名是“cpu.c”):

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <assert.h>
#include <stdio.h>

int main(int argc, char *argv[])
 {
    if (argc != 2) {
        fprintf(stderr, "usage: cpu <string>\n");
        exit(1);
    }

    char *str = argv[1];

    while (1) {
        sleep(1);
        printf("%s\n", str);
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

当我在终端中运行“./cpu 'A'”时,一切正常,我可以使用 Ctrl + C 终止它。但是,当我使用

./cpu A & ./cpu B & ./cpu C & ./cpu D &
Run Code Online (Sandbox Code Playgroud)

使程序的多个实例运行,并尝试使用 Ctrl + C,代码继续无限期地运行。我在网上看到 Ctrl + Z 可以工作,但没有帮助。有没有办法在不关闭终端的情况下结束4个程序的运行?我已经看过这个,但我不相信它能帮助解决我的问题。

c bash shell operating-system

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

使用折叠构建字符串,并希望通过分配正确的容量来加快速度

我在 Rust 结构中有一个实现,它构建了一个非常大的字符串,最终将写入文件。我想知道是否可以通过确保字符串变量具有适当的容量来加快速度,但它并没有按照我预期的方式工作。

这就是我所做的:

let sum = izip!(self.ts, self.x, self.y).fold(String::with_capacity(capacity), |acc, x| {
            format!("{}{}, {}, {}\n", acc, x.0, x.1, x.2)
        });
Run Code Online (Sandbox Code Playgroud)

我认为该字符串将累积到第一个参数中,因此我用必要的容量实例化了它。然而,通过检查从 ( ) 输出的字符串的容量sum,我可以发现我的假设是错误的。

有人可以帮助我理解我的理解fold是错误的吗?也许可以给出一个关于构建这个字符串的更好方法的提示?

fold rust pre-allocation

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

使用 u128 的包装类型扩展 Diesel 时出错

我在尝试创建 Diesel 默认情况下未实现的自定义类型时遇到了以下代码的U128困难u128。我的目标是将原u128语作为文本格式或数字(最好是数字)存储在 Postgresql 数据库中。

use std::io::Write;
use diesel::{AsExpression, deserialize, FromSqlRow, serialize};
use diesel::deserialize::{FromSql};
use diesel::pg::{Pg};
use diesel::serialize::{IsNull, Output, ToSql};
use diesel::sql_types::{Text};

#[derive(AsExpression, FromSqlRow, Debug, Clone, Copy)]
#[diesel(sql_type = Text)]
pub struct U128(pub u128);

impl ToSql<Text, Pg> for U128 {
    fn to_sql<'b>(&self, out: &mut Output<'b, '_, Pg>) -> serialize::Result {
        write!(out, "{}", self.0.to_string())?;
        Ok(IsNull::No)
    }
}

impl FromSql<Text, Pg> for U128 {
    fn from_sql(bytes: Option<&[u8]>) -> deserialize::Result<Self> {
        let s = String::from_utf8_lossy(bytes.as_bytes());
        Ok(U128(s.parse()?))
    } …
Run Code Online (Sandbox Code Playgroud)

postgresql rust rust-diesel

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

为什么 printf("%c", 0.21) 结果是 'ß'?

所以,这是我的 C 代码。当我为了学习格式说明符而摆弄我的代码时,尤其是%c

\n
#include <stdio.h>\n\nvoid main()\n{\n    double a = 0.21;\n    printf("%c", a);\n}\n
Run Code Online (Sandbox Code Playgroud)\n

我碰巧遇到这样的情况:即使我将浮点值作为printf()格式说明符的函数参数传递%c,编译器(我的编译器是gcc)也会以某种方式将该值转换为与 ASCII 字符相对应的0.21十进制值。223\xc3\x9f

\n

对于a = 0.22输出为:)其 ASCII 表中的十进制值为29

\n

我在VS codeCLion IDE上运行了代码,但结果是相同的。现在这让我摸不着头脑好几天了,我无法弄清楚。

\n

我想知道值0.210.22是如何转换成十进制的22329或者它们如何分别对应于 ASCII 223 和 29 ie\xc3\x9f)

\n

由于值 0.21、0.22 不对应于任何 ASCII,因此我希望程序不会打印任何内容。

\n

但根据输出,我认为这可能与二进制文件有关。
\n由于二进制中的 0.21 是 0.00110101110000101000111101011100...
\n& 223 是 11011111 …

c printf format-specifiers

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

仅具有原始类型的 Rust 结构仍然被移动?

所以,我在 Rust Book(布朗大学版本)中发现了这段代码:

#[derive(Debug)]
struct Rectangle {
    width: u32,
    height: u32,
}

fn main() {
    let rect1 = Rectangle {
        width: 30,
        height: 50,
    };
    let a = area(rect1);
    println!("{} * {} = {}", rect1.width, rect1.height, a);
}

fn area(rectangle: Rectangle) -> u32 {
    rectangle.width * rectangle.height
}
Run Code Online (Sandbox Code Playgroud)

该代码无法编译,因为当我们调用 时,area(rect1)我们移动了Rectangle. 但是Rectanglecontains 类型的字段u32是原始类型,因此实现了Copy特征。那么应该允许编译。我在这里缺少什么?

struct rust

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

chrono 将 DateTime&lt;Utc&gt; 转换为 NaiveDate

经过一段时间的摆弄后,我决定在这里问这个问题,因为 - 其他人不会像我一样浪费那么多的摆弄时间。

那么,如何将 a 转换DateTime<Utc>NaiveDateRustchrono箱子呢?

这是“填空”类型的测试代码:

#[test]
  fn test_utc_now_to_naive_date() {
    let utc_now = Utc::now();
    let now: NaiveDate = ???? // how?
  }
Run Code Online (Sandbox Code Playgroud)

我将这样一个事实归结为:在大多数语言中,时间和日期函数库都是过度设计的怪物,这归因于遭受 Y2K bug 的 PTSD 人们......

我们有这样的特征Datelike,难道这不会有助于将一个类似日期的东西转换成另一种吗?好吧 - 我找不到解决方案......

rust rust-chrono

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