如何指定函数采用 HashMap? [英] How do I specify that a function takes a HashMap?
问题描述
我如何指定一个非原始类型作为 Rust 函数参数——特别是一个 HashMap
?例如:
How do I specify a non-primitive type as a Rust function parameter - specifically, a HashMap
? For example:
use std::collections::HashMap;
// a main function that would call fibbonacci...
// Here the hashmap would be used for memoizing;
// maybe ugly, but it's a first attempt
fn fibbonacci(n: i32, cache: ??) -> i32 {
}
我试过了:
cache: Hashmap
=>类型参数数量错误:预期至少为 2,找到 0
cache: <HashMap>
=>error: expected ::, found )
缓存:std::collections::HashMap
=>类型参数的数量错误:预期至少为 2,发现为 0
cache: Hashmap
=>wrong number of type arguments: expected at least 2, found 0
cache: <HashMap>
=>error: expected ::, found )
cache: std::collections::HashMap
=>wrong number of type arguments: expected at least 2, found 0
这是 Rust 1.0.0.beta.
This is with Rust 1.0.0.beta.
推荐答案
让我们看看这段代码的编译器错误信息:
Let's check out the compiler error message for this code:
use std::collections::HashMap;
fn fibbonacci(n: i32, cache: HashMap) -> i32 {}
fn main() {}
我们得到:
error[E0243]: wrong number of type arguments: expected at least 2, found 0
--> src/main.rs:3:29
|
3 | fn fibonacci(n: i32, cache: HashMap) -> i32 {}
| ^^^^^^^ expected at least 2 type arguments
请注意,它直接指向问题并告诉您需要 2 个类型参数.Rust 要求函数参数和返回值完全拼写出来,此时没有类型推断.
Note that it points directly to the issue and tells you that you need 2 type arguments. Rust requires that function arguments and return values be fully spelled out, there is no type inference at this point.
我不知道你想要什么键和值,所以我假设 i32
:
I don't know what you want the keys and values to be, so I'll assume i32
:
fn fibonacci(n: i32, cache: HashMap<i32, i32>) -> i32 { 0 }
更详细地说,HashMap
有两个通用类型参数,简称为K
和V
(但请参见下面的注释).要引用HashMap
的具体类型,您需要指定K
和V
是什么.您还可以使用更多泛型类型,但将特征边界放在泛型上.这有点高级,您无需担心它即可开始使用 Rust!
More verbosely, HashMap
has two generic type parameters, referred to as K
and V
(but see note below). To reference a concrete type of HashMap
, you need to specify what K
and V
are. You can also use more generic types but place trait bounds on the generics. This is a bit more advanced, and you don't need to worry about it to get started with Rust!
注意 - HashMap
实际上有 3 个类型参数,但第三个有一个默认值并且不经常使用.该类型参数允许控制所使用的散列算法.
note - HashMap
actually has 3 type parameters, but the third has a default value and isn't often used. That type parameter allows controlling the hashing algorithm used.
这篇关于如何指定函数采用 HashMap?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!