我需要将 a 传递HashMap给一个函数,但HashMap理论上这可以同时具有整数和字符串作为值。我如何为此形成相关函数的类型签名?我是 Rust 的新手,在尝试fn do_thing(params: &HashMap<String, _>)并遇到失败之后,我没有任何想法。
fn do_thing(params: &HashMap<String, _>) {
// Irrelevant - regardless, the compiler fails because I cannot use the type placeholder in a function's type sig.
}
fn main() {
let params = HashMap::new();
params.insert(field, value); // field will always be a string, value could be a string or an integer
do_thing(¶ms)
}
Run Code Online (Sandbox Code Playgroud)
这不是建议问题的重复 - 构造 aHashMap不需要类型声明,而这涉及HashMap作为函数的参数,它需要。
如果您的值可以是 int 或 string,请使用enum如下:
use std::collections::HashMap;
enum Value {
Int(i32),
String(String),
}
fn do_thing(params: &HashMap<String, Value>) {
// each value of params can be Int or String. Check it with a match.
}
Run Code Online (Sandbox Code Playgroud)
如果Value是Int或 ,则检查匹配项String:
match val {
Value::Int(i) => //do something with i
Value::String(s) => //do something with s
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
951 次 |
| 最近记录: |