< 返回版块

枪炮与玫瑰 发表于 2018-09-21 10:39

Tags:drop,mut

如下面的代码所示, 因为声明的变量不是mut可变型,所以直接调用带有 &mut self的函数会出错,然后调drop()则不会

https://play.rust-lang.org/?gist=88fe2dfb4a51c14b42dde3e4e21c6302&version=stable&mode=debug&edition=2015;

[code] struct TestObject { v: i32 } trait DropSelf { fn drop_self(&mut self) { println!("---- drop_self call"); } } impl TestObject { fn show(v: &mut i32) { println!("show called {}",v); } fn test_mut(&mut self) { //self.v += 1; println!("self.v = {}", self.v); } }

impl Drop for TestObject { //我这里的函数签名是&mut self,但我传一个引用,也可以i编译过 fn drop(&mut self) { self.drop_self(); println!("drop called {}", self.v); }

}

impl DropSelf for TestObject {}

fn main() { let m1 = TestObject {v:1}; let m2 = TestObject {v:2}; let m3 = TestObject {v:3}; let mut data = 2; TestObject::show(&mut data); //m.test_mut(); //直接调用 test_mut()因为不是mut型会报错 let mut mm = m1; //强制let mut一次即可 mm.test_mut(); //drop(m); //m.drop_self(); } [/code]

梳理一下 @Richard 的问题应该是回收的时候, drop_in_place() 拿到所有权转移了,然后去干啥都行,let mut一次想怎么弄都行了

评论区

写评论

还没有评论

1 共 0 条评论, 1 页