2014-03-04 16:26:51 -06:00
|
|
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
|
|
|
|
// file at the top-level directory of this distribution and at
|
|
|
|
// http://rust-lang.org/COPYRIGHT.
|
|
|
|
//
|
|
|
|
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
|
|
|
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
|
|
|
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
|
|
|
// option. This file may not be copied, modified, or distributed
|
|
|
|
// except according to those terms.
|
|
|
|
|
2015-03-05 20:33:58 -06:00
|
|
|
#![feature(collections)]
|
|
|
|
|
2014-03-04 16:26:51 -06:00
|
|
|
use std::cell::RefCell;
|
|
|
|
use std::rc::Rc;
|
2014-05-22 18:57:53 -05:00
|
|
|
use std::string::String;
|
2014-03-04 16:26:51 -06:00
|
|
|
|
2015-01-28 07:34:18 -06:00
|
|
|
#[derive(PartialEq, Debug)]
|
2014-03-04 16:26:51 -06:00
|
|
|
struct Point {
|
2015-03-25 19:06:52 -05:00
|
|
|
x: isize,
|
|
|
|
y: isize
|
2014-03-04 16:26:51 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
pub fn main() {
|
2015-01-25 15:05:03 -06:00
|
|
|
assert_eq!(*Rc::new(5), 5);
|
2015-02-15 02:52:21 -06:00
|
|
|
assert_eq!(***Rc::new(Box::new(Box::new(5))), 5);
|
2014-03-04 16:26:51 -06:00
|
|
|
assert_eq!(*Rc::new(Point {x: 2, y: 4}), Point {x: 2, y: 4});
|
|
|
|
|
2015-01-25 15:05:03 -06:00
|
|
|
let i = Rc::new(RefCell::new(2));
|
2014-03-04 16:26:51 -06:00
|
|
|
let i_value = *(*i).borrow();
|
|
|
|
*(*i).borrow_mut() = 5;
|
|
|
|
assert_eq!((i_value, *(*i).borrow()), (2, 5));
|
|
|
|
|
2014-05-25 05:10:11 -05:00
|
|
|
let s = Rc::new("foo".to_string());
|
|
|
|
assert_eq!(*s, "foo".to_string());
|
2015-02-01 20:53:25 -06:00
|
|
|
assert_eq!((*s), "foo");
|
2014-03-04 16:26:51 -06:00
|
|
|
|
2015-06-08 09:55:35 -05:00
|
|
|
let mut_s = Rc::new(RefCell::new(String::from("foo")));
|
2014-03-04 16:26:51 -06:00
|
|
|
(*(*mut_s).borrow_mut()).push_str("bar");
|
2014-10-09 14:17:22 -05:00
|
|
|
// assert_eq! would panic here because it stores the LHS and RHS in two locals.
|
2015-06-07 13:00:38 -05:00
|
|
|
assert_eq!((*(*mut_s).borrow()), "foobar");
|
|
|
|
assert_eq!((*(*mut_s).borrow_mut()), "foobar");
|
2014-03-04 16:26:51 -06:00
|
|
|
|
|
|
|
let p = Rc::new(RefCell::new(Point {x: 1, y: 2}));
|
|
|
|
(*(*p).borrow_mut()).x = 3;
|
|
|
|
(*(*p).borrow_mut()).y += 3;
|
|
|
|
assert_eq!(*(*p).borrow(), Point {x: 3, y: 5});
|
|
|
|
|
2016-10-29 16:54:04 -05:00
|
|
|
let v = Rc::new(RefCell::new(vec![1, 2, 3]));
|
2014-11-06 11:25:16 -06:00
|
|
|
(*(*v).borrow_mut())[0] = 3;
|
|
|
|
(*(*v).borrow_mut())[1] += 3;
|
2014-10-15 01:05:01 -05:00
|
|
|
assert_eq!(((*(*v).borrow())[0],
|
|
|
|
(*(*v).borrow())[1],
|
|
|
|
(*(*v).borrow())[2]), (3, 5, 3));
|
2014-03-04 16:26:51 -06:00
|
|
|
}
|