Type signature of a Rust HashMap of a function

后端 未结 2 1827
时光说笑
时光说笑 2021-01-27 21:41

I create a HashMap which maps strings to functions of type Vec -> Expression, where Expression is a type I have defined. The code

2条回答
  •  梦谈多话
    2021-01-27 22:17

    The relevant parts of error message are Box and Box. The first is a boxed Fn trait object. The second is a boxed function plus. Note that it isn't a boxed pointer to a function, which would be Box with no {plus} part. It is the unique and unnameable type of the function plus itself.

    That is you cannot write real type of this HashMap, as the type it contains is unnameable. It's not a big deal though, you can only put plus function into it.

    The following code gives compilation error

    let functions: HashMap<_, _> =
        vec![("+", Box::new(plus)), 
             ("-", Box::new(minus))].into_iter().collect();
                            ^^^^^ expected fn item, found a different fn item
    

    This works, but it is useless

    let functions: HashMap<_, _> =
        vec![("+", Box::new(plus)), 
             ("-", Box::new(plus))].into_iter().collect();
    

    One possible solution is to convert first element of a vector into the required type.

    type BoxedFn = Box) -> Expression>;
    
    let functions: HashMap<&str, BoxedFn> =
        vec![("+", Box::new(plus) as BoxedFn),
             ("_", Box::new(minus))].into_iter().collect();
    

    Another one is type ascription of intermediate variable.

    type BoxedFn = Box) -> Expression>;
    
    let v: Vec<(_, BoxedFn)> = vec![("+", Box::new(plus)), ("_", Box::new(minus))];
    let functions: HashMap<&str, BoxedFn> = v.into_iter().collect();
    

提交回复
热议问题