[英]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 {
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.