如何将非基本类型指定为Rust函数参数 - 具体来说,是HashMap
?例如:
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 {
}
Run Code Online (Sandbox Code Playgroud)
我试过了:
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.
让我们看看这段代码的编译器错误消息:
use std::collections::HashMap;
fn fibbonacci(n: i32, cache: HashMap) -> i32 {}
fn main() {}
Run Code Online (Sandbox Code Playgroud)
我们得到:
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
Run Code Online (Sandbox Code Playgroud)
请注意,它直接指向问题,并告诉您需要2个类型参数.Rust要求完全拼写函数参数和返回值,此时没有类型推断.
我不知道你想要的键和值是什么,所以我假设i32
:
fn fibonacci(n: i32, cache: HashMap<i32, i32>) -> i32 { 0 }
Run Code Online (Sandbox Code Playgroud)
更详细地说,HashMap
有两个泛型类型参数,称为K
和V
(但请参见下面的注释).要引用具体类型HashMap
,您需要指定什么K
和V
是什么.您还可以使用更多泛型类型,但在泛型上放置特征边界.这有点高级,你不必担心它开始使用Rust!
注意 - HashMap
实际上有3个类型参数,但第三个具有默认值,并且不经常使用.该类型参数允许控制所使用的散列算法.
归档时间: |
|
查看次数: |
1615 次 |
最近记录: |