rust循环引用问题
Posted 吴冬冬
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了rust循环引用问题相关的知识,希望对你有一定的参考价值。
循环引用的时候需要使用weak,弱引用,一般把上级作为弱引用加到下级里
trait Sprite
fn draw(&self);
fn update(&self);
struct Ball
game: RefCell<Weak<Game>>,
impl Sprite for Ball
fn draw(&self)
fn update(&self)
let g = self.game.borrow_mut().upgrade().expect("");
let mut score = g.score.borrow_mut();
*score = 1;
struct Paddle
game: RefCell<Weak<Game>>,
impl Sprite for Paddle
fn draw(&self)
fn update(&self)
下级引用上级时普通的引用就OK了,要修改的就用RefCell
,不用修改的就使用Rc
struct Game
score: RefCell<i32>,
sprites: RefCell<Vec<Rc<Sprite>>>,
impl Game
fn draw(&mut self)
let ss = self.sprites.borrow_mut();
for s in ss.iter()
s.draw();
下面是调用的方式
fn main()
let ball = Rc::new(
Ball
game: RefCell::new(Weak::new())
);
let paddle = Rc::new(
Paddle
game: RefCell::new(Weak::new())
);
let mut game = Rc::new(
Game
score: RefCell::new(0),
sprites: RefCell::new(vec![Rc::clone(&ball) as Rc<Sprite>, Rc::clone(&paddle) as Rc<Sprite>]),
);
*ball.game.borrow_mut() = Rc::downgrade(&game);
*paddle.game.borrow_mut() = Rc::downgrade(&game);
ball.update();
println!("",game.score.borrow());
以上是关于rust循环引用问题的主要内容,如果未能解决你的问题,请参考以下文章
下级引用上级(相对导包):SystemError: Parent module '' not loaded, cannot perform relative import