gpt4 book ai didi

rust - 如何在 Rust 中制作调度表?

转载 作者:行者123 更新时间:2023-11-29 08:23:27 25 4
gpt4 key购买 nike

<分区>

我正在尝试构建一个简单的 RPN 计算器,并且我已经掌握了基础知识。我想做一个 dispatch table实现各种计算器功能。如果我在 Perl 中这样做,我会这样写:

my %ops = (
'+' => sub { +shift + +shift; },
'-' => sub { +shift - +shift; },
'*' => sub { +shift * +shift; },
'/' => sub { +shift / +shift; }
);

或者在 JavaScript 中:

let ops = {
"+": (a, b) => a + b,
"-": (a, b) => a - b,
"*": (a, b) => a * b,
"/": (a, b) => a / b
};

这是我迄今为止在 Rust 中尝试过的:

use std::collections::HashMap;

fn main() {
println!("Going to call +");

let dispatch = HashMap::new();

dispatch.insert(String::from("+"), |a, b| a + b);
dispatch.insert(String::from("-"), |a, b| a - b);

let plus = dispatch.get(&String::from("+"));
println!("2 + 3 = {}", plus(2, 3));

let minus = dispatch.get(&String::from("-"));
println!("2 - 3 = {}", minus(2, 3));
}

当我尝试编译时,出现以下错误:

error[E0308]: mismatched types
--> src/main.rs:9:40
|
9 | dispatch.insert(String::from("-"), |a, b| a - b);
| ^^^^^^^^^^^^ expected closure, found a different closure
|
= note: expected type `[closure@src/main.rs:8:40: 8:52]`
found type `[closure@src/main.rs:9:40: 9:52]`
= note: no two closures, even if identical, have the same type
= help: consider boxing your closure and/or using it as a trait object

error[E0618]: expected function, found enum variant `plus`
--> src/main.rs:12:28
|
11 | let plus = dispatch.get(&String::from("+"));
| ---- `plus` defined here
12 | println!("2 + 3 = {}", plus(2, 3));
| ^^^^^^^^^^ not a function
help: `plus` is a unit variant, you need to write it without the parenthesis
|
12 | println!("2 + 3 = {}", plus);
| ^^^^

error[E0618]: expected function, found enum variant `minus`
--> src/main.rs:15:28
|
14 | let minus = dispatch.get(&String::from("-"));
| ----- `minus` defined here
15 | println!("2 - 3 = {}", minus(2, 3));
| ^^^^^^^^^^^ not a function
help: `minus` is a unit variant, you need to write it without the parenthesis
|
15 | println!("2 - 3 = {}", minus);
| ^^^^^

“没有两个闭包,即使相同,也没有相同的类型”是什么意思?如何让 HashMap 持有一个闭包,然后调用它?

听起来使用 Box 可以解决问题...就像我说的,我是新手,我还没有使用过 Box。如何从盒子中取出盒子里的东西?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com