如何使用泛型调用结构的关联函数?

时间:2019-11-06 02:03:57

标签: rust

我试图用实现Link的泛型创建一个SinglLink特征和一个结构Link,但是当我调用该结构的关联函数时,出现了错误。我应该使用像vec!这样的宏吗?

mod Link {
    use std::cell::RefCell;
    use std::collections::VecDeque;
    use std::fmt::Debug;
    use std::rc::Rc;

    trait Link {
        type Node;
        type Value;
        fn new(data: &mut VecDeque<Self::Value>) -> Self;
    }

    #[derive(Debug)]
    pub struct Node<T> {
        pub value: T,
        pub next: RefCell<Option<Rc<Node<T>>>>,
    }

    #[derive(Debug)]
    pub struct SinglLink<T> {
        pub header: RefCell<Option<Rc<Node<T>>>>,
        pub len: i32,
    }

    impl<T: Copy> Link for SinglLink<T> {
        type Node = Node<T>;
        type Value = T;
        fn new(data: &mut VecDeque<Self::Value>) -> Self {
            SinglLink {
                header: RefCell::new(None),
                len: 0,
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::Link::SinglLink;
    use super::*;
    use std::cell::RefCell;
    use std::collections::VecDeque;

    #[test]
    fn it_works() {
        let mut data: VecDeque<i32> = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10].into_iter().collect();
        let single: SinglLink<i32> = SinglLink::new(&mut data);
    }
}

错误消息:

error[E0599]: no function or associated item named `new` found for type `Link::SinglLink<_>` in the current scope
  --> src/lib.rs:47:49
   |
20 |     pub struct SinglLink<T> {
   |     ----------------------- function or associated item `new` not found for this
...
47 |         let single: SinglLink<i32> = SinglLink::new(&mut data);
   |                                                 ^^^ function or associated item not found in `Link::SinglLink<_>`
   |
   = 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: `Link::Link`

1 个答案:

答案 0 :(得分:1)

这里有两个小错误,使错误消息不是很有帮助。

  1. 您已经忘记了pub上的trait Link,因此在Link模块之外完全无法访问。例如pub trait Link { /* ... */ }

  2. 您需要在use模块中Link的{​​{1}}特性才能在此处使用其方法。 (一旦添加tests,编译器错误将很好地告诉您)。例如pub

这是您代码的有效版本:

use super::Link::Link;

Rust Playground