目次

Rustの勉強[RefCell<T> その3 & Weak<T> その1]

(更新: )ぎじゅつ

はじめに

#

NO IMAGEThe Rust Programming Language 日本語版 - The Rust Programming Language 日本語版
を読んでいる

お勉強

#
  • RefCellをやっていた
  • RefCellから普遍や可変参照する方法
    • この答えはメソッド名は忘れたが特定のメソッドを呼ぶとderefが実装された型が返ってくる

NO IMAGERefCell<T>と内部可変性パターン - The Rust Programming Language 日本語版
ここやる

メモ

#

Rc<T>RefCell<T>を組み合わせることで可変なデータに複数の所有者を持たせる

  • 理解はできるな
  • Rc<RefCell<T>>かな
#[derive(Debug)]
enum List {
    Cons(Rc<RefCell<i32>>, Rc<List>),
    Nil,
}

use crate::List::{Cons, Nil};
use std::cell::RefCell;
use std::rc::Rc;

fn main() {
    let value = Rc::new(RefCell::new(5));

    let a = Rc::new(Cons(Rc::clone(&value), Rc::new(Nil)));

    let b = Cons(Rc::new(RefCell::new(3)), Rc::clone(&a));
    let c = Cons(Rc::new(RefCell::new(4)), Rc::clone(&a));

    *value.borrow_mut() += 10;

    println!("a after = {:?}", a);
    println!("b after = {:?}", b);
    println!("c after = {:?}", c);
}
  • やはりそうだね

  • Rc::clone(&a)

    • これしているからcountが3になるのかな
  • let a = Rc::new(Cons(Rc::clone(&value), Rc::new(Nil)));

    • これもか
    • ここでもいけるな
$ cargo run
Compiling cons-list v0.1.0 (file:///projects/cons-list)
Finished dev [unoptimized + debuginfo] target(s) in 0.63s
Running `target/debug/cons-list`
a after = Cons(RefCell { value: 15 }, Nil)
b after = Cons(RefCell { value: 3 }, Cons(RefCell { value: 15 }, Nil))
c after = Cons(RefCell { value: 4 }, Cons(RefCell { value: 15 }, Nil))
  • そうね、全部同じ値をポインタとして参照しているのか
  • やりたくねーこんな複雑なこと
  • RefCell終わった

NO IMAGE循環参照は、メモリをリークすることもある - The Rust Programming Language 日本語版

  • それはそうやろ
  • そもそも循環参照ってgoの静的解析で怒られなかったっけ

まとめ

#
  • 今回大して学びはない
  • 普通に使いたくないなとしか思わなかった