繁体   English   中英

Rust生存期和调用成员函数

[英]Rust lifetime and calling member function

我有一个关于Rust编程语言中varable的生存期的问题。

createTest函数创建并返回r值引用。 当它返回引用时, testValue被销毁。 但是test.print()不会导致崩溃。 为什么?

(Test :: print函数是否称为静态函数?)

struct Test;                                                         
impl Drop for Test {                                                       
  fn drop (&mut self) {                                                    
    println("Dropped.");                                                   
  }                                                                        
}                                                                          

impl Test {                                                                
  fn print(&self) { println!("Print!"); }                                  
}                                                                          

fn createTest() -> &Test {                                                 
  let testValue = &Test;                                                   
  return testValue;                                                        
}                                                                          

fn main() {                                                                
  let test = createTest();                                             
  test.print();                                                            
  println("Test");                                                         
}

结果

Dropped.
Print!
Test

代码编译的原因是因为使用单位结构(即没有字段)基本上等效于:

 struct Test;

 static TestStatic: Test = Test;

 fn createTest() -> &Test {
      &TestStatic
 }

因此, &TestStatic表达式的类型为&'static Test 每个生命周期都是'static的子生命周期,包括-> &Test的隐式匿名生命周期,因此您可以在其位置返回'static

此行为包含两个错误:


也就是说, Drop运行非常奇怪,因此感谢您提交11681

在我看来,这似乎是个错误。 您的示例的简单扩展无法使用绝对自然的错误消息进行编译:

struct Test {
    x: int
}

impl Drop for Test {
  fn drop (&mut self) {
    println("Dropped.");
  }
}

impl Test {
  fn print(&self) { println!("Print: {}", self.x); }
}

fn createTest() -> &Test {
  let testValue = &Test{ x: 10 };
  testValue
}

fn main() {
  let test = createTest();
  test.print();
  println("Test");
}

错误信息:

main.rs:16:19: 16:24 error: borrowed value does not live long enough
main.rs:16   let testValue = &Test{ x: 10 };
                             ^~~~~
main.rs:15:26: 18:2 note: reference must be valid for the anonymous lifetime #1 defined on the block at 15:25...
main.rs:15 fn createTest() -> &Test {
main.rs:16   let testValue = &Test{ x: 10 };
main.rs:17   testValue
main.rs:18 }
main.rs:15:26: 18:2 note: ...but borrowed value is only valid for the block at 15:25
main.rs:15 fn createTest() -> &Test {
main.rs:16   let testValue = &Test{ x: 10 };
main.rs:17   testValue
main.rs:18 }

顺便说一句,除非要提前返回(例如从循环内部),否则您无需编写return即可从函数中返回某些内容。 只需在最后一个语句中省略分号即可。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM