提问人:Akash R 提问时间:8/31/2023 更新时间:8/31/2023 访问量:29
在所有权的上下文中,需要对 Rust 中 Scope 和 Drop 调用的行为进行更多解释
Need more explanation in the behaviour of Scope and Drop call in Rust in the context of Ownership
问:
我是 Rust 的新手,对了解它的所有权概念感到好奇。根据官方文件,提到了以下关于概念的内容:referencing
下面介绍了如何定义和使用 calculate_length 函数,该函数将对对象的引用作为参数,而不是获取值的所有权:
fn main() {
let s1 = String::from("hello");
let len = calculate_length(&s1);
println!("The length of '{}' is {}.", s1, len);
}
fn calculate_length(s: &String) -> usize {
s.len()
}
&s1 语法允许我们创建一个引用 s1 值但不拥有它的引用。由于它不拥有它,因此当引用停止使用时,它指向的值不会被删除。
因此,在上面的场景中,仍然是可访问的,并且在函数结束之前不会超出范围,并且只有在函数结束之后才调用。但是,如果像这样将值传递给函数呢?s1
main
drop
main
calculate_length
let len = calculate_length(&String::from("hello"));
什么时候叫滴?这是谁?何时删除引用的 String 实例的值?我对此有点困惑,如果我能得到一个简单有效的解释,我将不胜感激。owner
String
答:
评论
&str
,而不是&String
。