【问题标题】:"use of undeclared type name" when using generic types使用泛型类型时“使用未声明的类型名称”
【发布时间】:2015-09-30 23:44:31
【问题描述】:

我正在用 Rust 编写并发字典的基本结构,首先将现有的 HashMap 简单地包装在 Arc::new(Mutex::new(hash_map_placeholder)) 中。然而,几乎我一开始,事情就开始出错了。我在将 <K, V> 值传递到普通的 HashMap 时遇到问题,所以我什至无法从包装版本开始。我目前收到以下错误:

concurrent_dictionary.rs:11:39: 11:40 error: use of undeclared type name `K`
concurrent_dictionary.rs:11 impl Default for ConcurrentDictionary<K, V> {
                                                              ^
concurrent_dictionary.rs:11:42: 11:43 error: use of undeclared type name `V`
concurrent_dictionary.rs:11 impl Default for ConcurrentDictionary<K, V> {

我知道这与未正确传递的类型名称有关。如何做到这一点?即使我摆脱了默认的 impl,我仍然需要为 ConcurrentDictionary::new() 编写相同的内容。代码如下:

use std::collections::HashMap;
use std::default::Default;

#[derive(Clone)]
pub struct ConcurrentDictionary<K, V> {
    data: HashMap<K, V>, 
}

impl Default for ConcurrentDictionary<K, V> {
    #[inline]
    fn default() -> ConcurrentDictionary<K, V> {
        ConcurrentDictionary {
            data: HashMap::<K, V>::new(),
        }   
    }   
}

impl<K, V> ConcurrentDictionary<K, V> {
    #[inline]
    pub fn new() -> ConcurrentDictionary<K, V> {
        Default::default()
    }   
}

【问题讨论】:

    标签: types rust


    【解决方案1】:

    您需要声明您使用的任何泛型类型:

    impl<K, V> Default for ConcurrentDictionary<K, V> {
    

    之后,您会遇到KV 过于泛型的问题,您需要将它们限制为实现EqHash 的类型:

    impl<K, V> Default for ConcurrentDictionary<K, V>
        where K: std::cmp::Eq + std::hash::Hash
    

    您需要对调用函数应用相同的限制。

    【讨论】:

    • 完美,谢谢!我只是想让语法正确。现在我遇到了一个文档测试错误,但我非常希望自己能解决这个问题。
    • @NuclearAlchemist 如果您遇到任何问题,请随时回来搜索/问另一个问题!
    猜你喜欢
    • 1970-01-01
    • 2018-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多