我最近看到使用dyn关键字的代码:
fn foo(arg: &dyn Display) {}
fn bar() -> Box<dyn Display> {}
这个语法是什么意思?
为编写异步路由器时,我无法处理异步功能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());
}
生成以下编译器错误:
use std::collections::HashMap;
use std::future::Future;
type …为什么下面的代码会出错?[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();
}
错误:
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> …我的理解是,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>());
}
为什么E1按预期占用8个字节,但E2占用16个字节?
我有一个包含多个键和值的源 JSON,我想获取多个目标 JSON 并检查它们是否是该 JSON 的子集:目标 JSON 中的所有字段都存在于源 JSON 中并保持相同的值。
为了实现这一点,我想在 a 的值部分放置几个不同类型的值HashMap并调用equals这些值。
地图中有几种类型的值,我想接受一些键值对并检查是否
这是我想在 Java 中做的一个例子:
boolean isInMap(Map<String, Object> map, String key, Object value) {
    return map.containsKey(key) && map.get(key).equals(value);
}
这可能是一个XY 问题,但我如何在 Rust 中做到这一点?
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");
}
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 …我有这个功能:
async fn get_events(r: RequestBuilder) -> Result<Vec<RepoEvent>, reqwest::Error> {
    Ok(r.send().await?.json::<Vec<RepoEvent>>().await?)
}
我想存储一个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();
我得到一个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);
});
但我真的很想知道如何将 future 存储在向量中。
我有一个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],
            _ => {}
        }
    } …在使用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());
}
上面的代码当然不能编译,因为to_string()没有定义方法Operator.我看到两种解决方法:
to_string()方法Operator.我认为第二个是首选,但我不知道创建引用向量是否会引入很多复杂性.