RUST内存管理(二)-所有权.md

所有权

rust通过所有权来管理内存的申请与释放,与gc和手动管理不同,走了第三条路。《rust所有权》原文地址

所有权的规则

先说明Rust中的所有权规则,如下:

  • rust中每个值都有一个所有者(Each value in Rust has an owner)。
  • 在同一时间只能有一个所有者(There can only be one owner at a time)。
  • 离开所有者的作用域,删除值(When the owner goes out of scope, the value will be dropped)。

所有权与函数

将值传递给函数在语义上与给变量赋值相似。向函数传递值可能会移动或者复制,就像赋值语句一样,取决于变量储存的位置。

fn main() {
let a = "a";
a_fun(a);
println!("{a}");
/// a 发生了赋值,a的值在stack中存储。
/// 此作用域中还存在,有效,
let b = String::from("string-from");
b_fun(b);
println!("{b}");
/// error[E0382]: borrow of moved value: `b`
/// --> src\main.rs:8:16
/// |
/// 6 | let b = String::from("string-from");
/// | - move occurs because `b` has type `String`, which does not implement the `Copy` trait
/// 7 | b_fun(b);
/// | - value moved here
/// 8 | println!("{b}");
/// | ^ value borrowed here after move
/// |
/// = note: this error originates in the macro `$crate::format_args_nl` (in Nightly builds, run with -Z macro-backtrace for more info)
///
/// b的数据在heap中,发生了移动。此作用域中b在传入函数中之后失效了,
}
fn a_fun(x: &str) {
println!("{x}")
}
fn b_fun(x: String) {
println!("{x}")
}

返回值与作用域

返回值也可以转移所有权。

fn main() {
let s1 = gives_ownership(); // gives_ownership 将返回值
// 移给 s1
let s2 = String::from("hello"); // s2 进入作用域
let s3 = takes_and_gives_back(s2); // s2 被移动到
// takes_and_gives_back 中,
// 它也将返回值移给 s3
} // 这里, s3 移出作用域并被丢弃。s2 也移出作用域,但已被移走,
// 所以什么也不会发生。s1 移出作用域并被丢弃
fn gives_ownership() -> String { // gives_ownership 将返回值移动给
// 调用它的函数
let some_string = String::from("yours"); // some_string 进入作用域
some_string // 返回 some_string 并移出给调用的函数
}
// takes_and_gives_back 将传入字符串并返回该值
fn takes_and_gives_back(a_string: String) -> String { // a_string 进入作用域
a_string // 返回 a_string 并移出给调用的函数
}
posted @   咕咚!  阅读(95)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示