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 {
}
I've tried:
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
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() {}
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. Rust requires that function arguments and return values be fully spelled out, there is no type inference at this point.
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 }
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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With