Skip to content

Instantly share code, notes, and snippets.

@kawakami-o3
Last active March 25, 2019 05:50
Show Gist options
  • Save kawakami-o3/d9ea1ad8a6ffe75e17f0f81aef9281b9 to your computer and use it in GitHub Desktop.
Save kawakami-o3/d9ea1ad8a6ffe75e17f0f81aef9281b9 to your computer and use it in GitHub Desktop.
Rust Rc RefCell
use std::rc::Rc;
use std::cell::RefCell;
/*
#[derive(Clone, Debug)]
struct Node {
val: i32,
ptr: Option<Rc<Node>>,
}
fn new_node(val: i32, ptr: Option<Rc<Node>>) -> Node {
Node {
val: val,
ptr: ptr,
}
}
fn nest(n: Node, count: i32) -> Node {
let mut i = count;
let mut m = n;
while i > 0 {
m = new_node(i, Some(Rc::new(m)));
i -= 1;
}
m
}
fn trial1() {
let mut n = Node {
val: 0,
ptr: None,
};
let p = &mut n as *mut Node;
let m = nest(n, 3);
println!("> {:?}", m);
unsafe {
(*p).val = 10;
}
println!("> {:?}", m);
}
*/
/*
fn trial2() {
let n = &mut Node {
val: 0,
ptr: None,
} as *mut Node;
let m = nest(*n, 3);
println!("> {:?}", m);
unsafe {
(*n).val = 10;
}
println!("> {:?}", m);
}
*/
/*
#[derive(Clone, Debug)]
struct Leaf {
val: i32,
ptr: Option<*mut Leaf>,
}
fn new_leaf(val: i32, ptr: Option<*mut Leaf>) -> *mut Leaf {
&mut Leaf {
val: val,
ptr: ptr,
} as *mut Leaf
}
fn nest_leaf(n: *mut Leaf, count: i32) -> *mut Leaf {
let mut i = count;
let mut m = n;
while i > 0 {
m = new_leaf(i, Some(m));
i -= 1;
}
m
}
fn trial3() {
let n = &mut Leaf {
val: 0,
ptr: None,
} as *mut Leaf;
let m = nest_leaf(n, 3);
unsafe {
// SIGILL
println!("> {:?}", *m);
}
unsafe {
(*n).val = 10;
}
unsafe {
println!("> {:?}", *m);
}
}
*/
#[derive(Clone, Debug)]
struct Node {
val: i32,
ptr: Option<Rc<RefCell<Node>>>,
}
fn new_node(val: i32, ptr: Option<Rc<RefCell<Node>>>) -> Node {
Node {
val: val,
ptr: ptr,
}
}
fn nest(n: Rc<RefCell<Node>>, count: i32) -> Rc<RefCell<Node>> {
let mut i = count;
let mut m = n;
while i > 0 {
//m = new_node(i, Some(Rc::new(RefCell::new(m))));
m = Rc::new(RefCell::new(new_node(i, Some(m))));
i -= 1;
}
m
}
fn trial4() {
let n = Rc::new(RefCell::new(Node {
val: 0,
ptr: None,
}));
let placeholder = n.clone();
let m = nest(n, 3);
println!("> {:?}", m);
placeholder.borrow_mut().val = 10;
println!("> {:?}", m);
}
fn main() {
/*
//https://qiita.com/keiSunagawa/items/a6cad9e6910f71dca44f
let c = Rc::new(RefCell::new("aaa"));
let c2 = c.clone();
*c.borrow_mut() = "bbb";
println!("{}", c2.borrow())
*/
trial4();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment