为什么impl不在范围内

问题描述 投票:1回答:1

我是Rust新手,在我的学习玩具项目中,我需要一个带有可变节点的图形数据结构,所以我想出了:

use std::cell::RefCell;
use std::clone::Clone;
use std::cmp::Eq;
use std::collections::HashMap;
use std::hash::Hash;
use std::rc::Rc;

pub trait Constructible<T> {
    type C;
    fn new(Self::C) -> T;
}

#[derive(Debug)]
pub struct HashedGraph<K: Eq + Hash + Clone, T: Constructible<T>> {
    graph: HashMap<K, Rc<RefCell<T>>>,
}

impl<K, T> HashedGraph<K, T>
where
    K: Eq + Hash + Clone,
    T: Constructible<T>,
{
    pub fn new<C>(connections: HashMap<K, C>) -> HashedGraph<K, T> {
        let mut graph: HashMap<K, Rc<RefCell<T>>> = HashMap::new();

        for key in connections.keys() {
            graph.insert(
                key.clone(),
                Rc::new(RefCell::new(C::new(*connections.get(key).unwrap()))),
            );
        }

        HashedGraph { graph }
    }
}

impl Constructible<String> for String {
    type C = String;
    fn new(instring: String) -> String {
        instring
    }
}

fn main() {
    let mut test = HashMap::new();
    test.insert("one", "ONE");
    test.insert("two", "TWO");
    let hg = HashedGraph::new(test);
}

我的想法是,我希望节点可以从另一种数据类型构建,但是这些数据不包含在图中,因此是一个关联类型而不是通用参数。节点T稍后将包含连接,这些连接只是指向其他节点的弱指针,但对于这个问题并不是真正相关的。编译时我得到一个错误:

error[E0599]: no function or associated item named `new` found for type `C` in the current scope
  --> src/main.rs:26:61
   |
26 |             graph.insert(key.clone(), Rc::new(RefCell::new( C::new( *connections.get(key).unwrap() ))));
   |                                                             ^^^^^^ function or associated item not found in `C`
   |
   = help: items from traits can only be used if the trait is implemented and in scope
   = note: the following trait defines an item `new`, perhaps you need to implement it:
           candidate #1: `Constructible`

我不明白为什么可构造的实现不在范围内或者其他什么不正确。如果这是实现这一目标的一种单一方式,我将非常乐意收到建议!

generics rust associated-types
1个回答
1
投票

new<C>()的声明中,类型参数C是一个没有约束的新类型变量。看来你打算将它作为TConstructible实例的关联类型,你可以这样表达:

pub fn new(connections: HashMap<K, T::C>) -> HashedGraph<K, T> {
 ...
}

您的代码还有许多其他问题:

  • 您正在使用&str实例化对象,但您只为Constructible添加了String实例。这些是不同的类型。
  • 您不需要使用hashmap.get(key)来访问该值。您可以使用iter() - 或者在这种情况下使用drain(),因为您无论如何都要将所有值从一个容器移动到另一个容器,因此如果您不需要原始的HashMap,这将避免借用问题。
  • Constructible的类型参数是多余的。这总是Self
  • T中可以推断fn new() -> T的唯一方法是来自呼叫者选择使用它的地方。从理论上讲,Constructible的另一个实现可能具有相同的C类型,因此这还不够。这意味着在构造HashedGraph时需要输入类型注释。

Here's a version of your code编译,虽然我对你真正想要达到的目标做了一些假设。

© www.soinside.com 2019 - 2024. All rights reserved.