Rust 如何返回变量;让我们;内部功能允许生锈吗?
编译并返回“预期”输出。但这不是一个悬而未决的指针场景吗?如果是这样,为什么rust编译器允许这样做Rust 如何返回变量;让我们;内部功能允许生锈吗?,rust,dangling-pointer,Rust,Dangling Pointer,编译并返回“预期”输出。但这不是一个悬而未决的指针场景吗?如果是这样,为什么rust编译器允许这样做 use serde_json::{Value, json}; use std::io::Result; fn main(){ println!("{:#?}", test_json_lifetime()); } fn test_json_lifetime() -> Result<(Value)> { l
use serde_json::{Value, json};
use std::io::Result;
fn main(){
println!("{:#?}", test_json_lifetime());
}
fn test_json_lifetime() -> Result<(Value)> {
let j = json!({ "name" : "test" });
Ok(j)
}
使用serde_json::{Value,json};
使用std::io::Result;
fn main(){
println!(“{:?}”,test_json_lifety());
}
fn test_json_lifety()->结果{
设j=json!({“name”:“test”});
Ok(j)
}
我在中找到了答案
听起来您好像认为
j
是在test\u json\u lifetime()
的堆栈框架上分配的(当堆栈展开时,内存在函数末尾被释放),我们返回了对j
的引用(这将导致指针悬空)
在这种情况下,j
在堆栈上分配是正确的,但是当我们返回Ok(j)
时,我们不会返回对j
的引用,而是将j
复制到main()上分配的结果的空间中的堆栈帧,在调用test\u json\u lifetime()函数之前
fn main() {
let s1 = gives_ownership(); // gives_ownership moves its return
// value into s1
let s2 = String::from("hello"); // s2 comes into scope
let s3 = takes_and_gives_back(s2); // s2 is moved into
// takes_and_gives_back, which also
// moves its return value into s3
}
// Here, s3 goes out of scope and is dropped. s2 goes out of scope but was
// moved, so nothing happens. s1 goes out of scope and is dropped.
fn gives_ownership() -> String { // gives_ownership will move its
// return value into the function
// that calls it
let some_string = String::from("hello"); // some_string comes into scope
some_string // some_string is returned and
// moves out to the calling
// function
}