只有在实施特征和范围时才能使用特征中的项目

时间:2017-10-25 20:08:48

标签: scope rust traits

我尝试从 Heads-up Design Patterns 实现Observer模式,该模式最初是用Java编写的:

use std::cell::RefCell;
use std::rc::Rc;
use std::borrow::BorrowMut;

trait Subject {
    fn registerObserver(&mut self, observer: Rc<RefCell<Observer>>);
    fn removeObserver(&mut self, observer: Rc<RefCell<Observer>>);
    fn notifyObserver(&self, observer: Rc<RefCell<Observer>>);
}

trait Observer {
    fn update(&mut self, data: f32);
}


struct Teacher {
    observers: Vec<Rc<RefCell<Observer>>>,
    data: f32,
}
impl Teacher {
    pub fn print(&self) {
        println!("teacher = {:}", self.data);
    }
}
impl Subject for Teacher {
    fn registerObserver(&mut self, observer: Rc<RefCell<Observer>>) {
        self.observers.push(observer);
    }
    fn removeObserver(&mut self, observer: Rc<RefCell<Observer>>) {
        println!("Teacher.removeObserver(...) not implemented yet...")
    }
    fn notifyObserver(&self, observer: Rc<RefCell<Observer>>) {
        for observer in self.observers {
            let mut loc_obs = observer.borrow_mut();
            loc_obs.update(self.data);
        }
    }
}

struct Student {
    data: f32,
}
impl Student {
    pub fn print(&self) {
        println!("student = {:}", self.data);
    }
}
impl Observer for Student {
    fn update(&mut self, data: f32) {
        self.data = data;
    }
}



fn main() {
    let mut teacher = Teacher {
        observers: Vec::new(),
        data: 42.,
    };
    teacher.print();
}

Playground

编译器告诉我

error[E0599]: no method named `update` found for type `&mut std::rc::Rc<std::cell::RefCell<Observer + 'static>>` in the current scope
  --> src/main.rs:35:21
   |
35 |             loc_obs.update(self.data);
   |                     ^^^^^^
   |
   = help: items from traits can only be used if the trait is implemented and in scope
   = note: the following trait defines an item `update`, perhaps you need to implement it:
           candidate #1: `Observer`

我的错误在哪里?

1 个答案:

答案 0 :(得分:3)

use std::borrow::BorrowMut;

您引入了特征BorrowMut,它定义了特征方法BorrowMut::borrow_mut阴影固有方法RefCell::borrow_mut。你可以告诉这个,因为你的类型不符合你的期望:

  

表示类型&mut std::rc::Rc<std::cell::RefCell<Observer + 'static>>

最简单的解决方法是删除该导入。您还可以disambiguate between them

然后,您还有进一步的问题,试图取得借来的价值和许多非惯用名称的所有权,这些名称会产生大量警告。你应该解决所有这些问题。