Skip to content

Instantly share code, notes, and snippets.

@tomoima525
Forked from rust-play/playground.rs
Last active September 17, 2021 21:35
Show Gist options
  • Save tomoima525/fff214d6a86ae943125ae5d9b81a8bae to your computer and use it in GitHub Desktop.
Save tomoima525/fff214d6a86ae943125ae5d9b81a8bae to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
// use std::cell::RefCell;
// Ownership: Copy semantic
// Copy trait should not have Drop trait implemented
#[derive(Debug, Clone, Copy)]
struct Parent(usize, Child, Child);
#[derive(Debug, Clone, Copy)]
struct Child(usize);
fn main() {
let p1 = Parent(1, Child(11), Child(12));
let p2 = p1;
println!("a: p2:{:?}", p2);
println!("a: p1:{:?}", p1);
}
// use std::cell::RefCell;
// Ownership: Lifecycle
#[derive(Debug)]
struct Parent(usize, Child, Child);
#[derive(Debug)]
struct Child(usize);
fn check_value(p: &Parent) {
println!("value {:?}", p)
}
fn change_value(p: &mut Parent) {
p.0 = 100;
}
fn main() {
let mut p1 = Parent(1, Child(11), Child(12));
check_value(&p1);
change_value(&mut p1);
println!("a: p1:{:?}", p1);
}
// value Parent(1, Child(11), Child(12))
// a: p1:Parent(100, Child(11), Child(12))
// use std::cell::RefCell;
// Ownership: Move Semantic
use {
std::ops::Drop
};
#[derive(Debug)]
struct Parent(usize, Child, Child);
#[derive(Debug)]
struct Child(usize);
impl Drop for Parent {
fn drop(&mut self) {
println!("Dropping {:?}", self);
}
}
impl Drop for Child {
fn drop(&mut self) {
println!("Dropping {:?}", self);
}
}
fn main() {
//let mut rc1 = Rc::new(Child(1));
let p1 = Parent(1, Child(11), Child(12));
let p2 = p1;
println!("a: p2:{:?}", p2);
println!("a: p1:{:?}", p1);
// |
//29 | let p1 = Parent(1, Child(11), Child(12));
// | -- move occurs because `p1` has type `Parent`, which does not implement the `Copy` trait
//30 | let p2 = p1;
// | -- value moved here
//31 | println!("a: p2:{:?}", p2);
//32 | println!("a: p1:{:?}", p1);
// | ^^ value borrowed here after move
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment