gpt4 book ai didi

scope - 特征中的项目只能在特征已实现且在范围内时使用

转载 作者:行者123 更新时间:2023-11-29 08:06:10 25 4
gpt4 key购买 nike

我尝试从 Heads-up Design Patterns 中实现观察者模式,它最初是用 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`

我的错误在哪里?

最佳答案

use std::borrow::BorrowMut;

你引入了特征 BorrowMut ,它定义了特征方法 BorrowMut::borrow_mut , 隐藏 固有方法 RefCell::borrow_mut .你可以这样说,因为你的类型不是你所期望的:

for type &mut std::rc::Rc<std::cell::RefCell<Observer + 'static>>

最简单的修复方法是删除该导入。您也可以disambiguate between them .

然后,您会遇到进一步的问题,即尝试获取借用值的所有权以及大量会产生大量警告的非惯用名称。你应该解决所有这些问题。

关于scope - 特征中的项目只能在特征已实现且在范围内时使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46941218/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com