[英]How do I specify that a function takes a HashMap?
How do I specify a non-primitive type as a Rust function parameter - specifically, a HashMap
? 如何将非基本类型指定为Rust函数参数 - 特别是
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 {
}
I've tried: 我试过了:
cache: Hashmap
=> wrong number of type arguments: expected at least 2, found 0
cache: Hashmap
=> wrong number of type arguments: expected at least 2, found 0
cache: <HashMap>
=> error: expected ::, found )
cache: <HashMap>
=> error: expected ::, found )
cache: std::collections::HashMap
=> wrong number of type arguments: expected at least 2, found 0
cache: std::collections::HashMap
=> wrong number of type arguments: expected at least 2, found 0
This is with Rust 1.0.0.beta. 这是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() {}
We get: 我们得到:
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
Note that it points directly to the issue and tells you that you need 2 type arguments . 请注意,它直接指向问题,并告诉您需要2个类型参数 。 Rust requires that function arguments and return values be fully spelled out, there is no type inference at this point.
Rust要求完全拼写函数参数和返回值,此时没有类型推断。
I don't know what you want the keys and values to be, so I'll assume i32
: 我不知道你想要的键和值是什么,所以我假设
i32
:
fn fibonacci(n: i32, cache: HashMap<i32, i32>) -> i32 { 0 }
More verbosely, HashMap
has two generic type parameters , referred to as K
and V
(but see note below). 更详细地说,
HashMap
有两个泛型类型参数 ,称为K
和V
(但请参见下面的注释)。 To reference a concrete type of HashMap
, you need to specify what K
and V
are. 要引用具体类型的
HashMap
,您需要指定K
和V
是什么。 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!
这有点高级,你不必担心它开始使用Rust!
note - HashMap
actually has 3 type parameters, but the third has a default value and isn't often used. 注意 -
HashMap
实际上有3个类型参数,但第三个具有默认值,并且不经常使用。 That type parameter allows controlling the hashing algorithm used. 该类型参数允许控制所使用的散列算法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.