相关疑难解决方法(0)

"dyn"在一个类型中意味着什么?

我最近看到使用dyn关键字的代码:

fn foo(arg: &dyn Display) {}

fn bar() -> Box<dyn Display> {}
Run Code Online (Sandbox Code Playgroud)

这个语法是什么意思?

syntax rust

41
推荐指数
3
解决办法
2788
查看次数

什么使某事成为"特质对象"?

最近的Rust改变使得"特质对象"对我来说更加突出,但我只是模糊地掌握了什么让某些东西成为特质对象.特别是一个变化是允许特征对象将特征实现转发到内部类型的即将发生的变化.

鉴于一个特点Foo,我很确定这Box<Foo>是一个特质对象.是否&Foo也是一个特质对象?那么其他智能指针之类的东西Rc还是Arc?我怎样才能创建自己的类型作为特征对象呢?

引用只提到一次trait对象,但没有提到定义.

traits rust

38
推荐指数
3
解决办法
5858
查看次数

如何在Rust中将异步函数放入地图中?

为编写异步路由器时,我无法处理异步功能hyper

这段代码:

use std::collections::HashMap;
use std::future::Future;

type BoxedResult<T> = Result<T, Box<dyn std::error::Error + Send + Sync>>;
type CalcFn = Box<dyn Fn(i32, i32) -> dyn Future<Output = BoxedResult<i32>>>;

async fn add(a: i32, b: i32) -> BoxedResult<i32> {
    Ok(a + b)
}

async fn sub(a: i32, b: i32) -> BoxedResult<i32> {
    Ok(a - b)
}

fn main() {
    let mut map: HashMap<&str, CalcFn> = Default::default();
    map.insert("add", Box::new(add));
    map.insert("sub", Box::new(sub));

    println!("map size: {}", map.len());
}
Run Code Online (Sandbox Code Playgroud)

生成以下编译器错误:

use std::collections::HashMap;
use std::future::Future;

type …
Run Code Online (Sandbox Code Playgroud)

rust async-await

10
推荐指数
1
解决办法
176
查看次数

如何使用数组填充特征对象向量?

为什么下面的代码会出错?[T; N]into有一个全面的实现Vec<T>,那么为什么在这种情况下dyn Foo不匹配呢?Fooable是否有不涉及克隆的解决方法Fooable

trait Foo {}

struct Fooable {}

impl Foo for Fooable {}

pub fn main() {
    let bar: Vec<Box<dyn Foo>> = [
        Box::new(Fooable {}),
    ].into();
}
Run Code Online (Sandbox Code Playgroud)

错误:

error[E0277]: the trait bound `Vec<Box<dyn Foo>>: From<[Box<Fooable>; 1]>` is not satisfied
  --> src/main.rs:10:7
   |
10 |     ].into();
   |       ^^^^ the trait `From<[Box<Fooable>; 1]>` is not implemented for `Vec<Box<dyn Foo>>`
   |
   = help: the following other types implement trait `From<T>`:
             <Vec<T, A> …
Run Code Online (Sandbox Code Playgroud)

rust

10
推荐指数
2
解决办法
1290
查看次数

为什么枚举需要额外的内存大小?

我的理解是,enum就像union在C中一样,系统将在枚举中分配最大的数据类型.

enum E1 {
    DblVal1(f64),
}

enum E2 {
    DblVal1(f64),
    DblVal2(f64),
    DblVal3(f64),
    DblVal4(f64),
}

fn main() {
    println!("Size is {}", std::mem::size_of::<E1>());
    println!("Size is {}", std::mem::size_of::<E2>());
}
Run Code Online (Sandbox Code Playgroud)

为什么E1按预期占用8个字节,但E2占用16个字节?

rust

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

如何创建不同类型的 HashMap 并测试它们是否相等?

我有一个包含多个键和值的源 JSON,我想获取多个目标 JSON 并检查它们是否是该 JSON 的子集:目标 JSON 中的所有字段都存在于源 JSON 中并保持相同的值。

为了实现这一点,我想在 a 的值部分放置几个不同类型的值HashMap并调用equals这些值。

地图中有几种类型的值,我想接受一些键值对并检查是否

  1. 钥匙在地图上
  2. 该值与地图中的值相同。

这是我想在 Java 中做的一个例子:

boolean isInMap(Map<String, Object> map, String key, Object value) {
    return map.containsKey(key) && map.get(key).equals(value);
}
Run Code Online (Sandbox Code Playgroud)

这可能是一个XY 问题,但我如何在 Rust 中做到这一点?

rust

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

How to execute multiple async functions at once and get the results?

I have tried Tokio tasks, but there are no working examples to execute multiple tasks at once. What is wrong with this code?

fn main() {
    block_on(speak());
}

async fn speak() {
    let hold = vec![say(), greet()];
    let results = join_all(hold).await;
}

async fn say() {
    println!("hello");
}

async fn greet() {
    println!("world");
}
Run Code Online (Sandbox Code Playgroud)

here is the compiler output

error[E0308]: mismatched types
  --> sync\src\main.rs:14:27
   |
14 |     let hold = vec![say(),greet()];
   |                           ^^^^^^^ expected opaque type, found a different opaque …
Run Code Online (Sandbox Code Playgroud)

rust async-await rust-tokio

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

如何创建未来的 Vec

我有这个功能:

async fn get_events(r: RequestBuilder) -> Result<Vec<RepoEvent>, reqwest::Error> {
    Ok(r.send().await?.json::<Vec<RepoEvent>>().await?)
}
Run Code Online (Sandbox Code Playgroud)

我想存储一个Vecfuture 并等待它们全部:

let mut events = vec![];
for i in 1..=x {
    let req: RequestBuilder = client.get(&format!("https://example.com/api?page={}", i));

    events.append(get_events(req));
}
try_join_all(events).await.unwrap();
Run Code Online (Sandbox Code Playgroud)

我得到一个E0308: expected mutable reference, found opaque type.

应该是什么类型events

我可以通过推断类型来解决问题:

let events = (1..=x).map(|i| {
    let req: RequestBuilder = client.get(&format!("https://example.com/api?page={}", i));

    get_events(req);
});
Run Code Online (Sandbox Code Playgroud)

但我真的很想知道如何将 future 存储在向量中。

rust rust-async-std

5
推荐指数
0
解决办法
1638
查看次数

尝试从函数返回 dyn Traits 向量时,“在编译时无法知道类型值的大小”

我有一个Processor::process可以返回函数动态向量的函数。当我尝试使用它时出现错误:

(dyn FnMut(String, Option<Vec<u8>>) -> Option<u8> + 'static)错误[E0277]:编译时无法知道类型值的大小

这是我的代码:

fn handler1(a: String, b: Option<Vec<u8>>) -> Option<u8> {
    None
}

fn handler2(a: String, b: Option<Vec<u8>>) -> Option<u8> {
    None
}

fn handler3(a: String, b: Option<Vec<u8>>) -> Option<u8> {
    None
}

struct Processor {}
impl Processor {
    pub fn process(data: u8) -> Vec<dyn FnMut(String, Option<Vec<u8>>) -> Option<u8>> {
        return match data {
            1 => vec![handler1],
            2 => vec![handler1, handler2],
            3 => vec![handler1, handler2, handler3],
            _ => {}
        }
    } …
Run Code Online (Sandbox Code Playgroud)

rust

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

矢量存储Rust中混合的数据类型

在使用Shunting-yard算法将中缀表达式转换为后缀表达式的上下文中.我想使用向量来存储输出,它将存储运算符和数值类型数据.

#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Operator {
    Add,
    Sub,
    Mul,
    Div,
}

fn main() {
    let mut output: Vec<String> = Vec::new();  // create an output vector
    let a = 2;
    let b = Operator::Add;
    let c = 3;
    output.push(a.to_string());
    output.push(b.to_string());
    output.push(c.to_string());
}
Run Code Online (Sandbox Code Playgroud)

上面的代码当然不能编译,因为to_string()没有定义方法Operator.我看到两种解决方法:

  1. 定义一个to_string()方法
  2. 创建一个向量来存储对数字的引用Operator.

我认为第二个是首选,但我不知道创建引用向量是否会引入很多复杂性.

vector type-conversion rust

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