ownership

Reference and Borrowing

In Rust, we use sign & to refer a variable, so as in C++.

Reference can be used as a constant parameter passed to functions, which means it is not allowed to change the original value of the parameter caused it's borrowed from another variable.

If you want to change the value, use mutable reference: &mut.

But mutable reference has a big restriction: only one mutable reference of a particular piece of data is allowed in a particular scope.

It's pretty useful when there is no mechanism being used to synchronize access to the data.

Also, when there is an immutable reference to a variable, any mutable references are not allowed either. Obviously user won't expect any mutable references when there is an immutable reference. Otherwise, the behavior of the immutable reference will be unexpected.

Note that a reference's scope from where it is introduced and continues through the last time that reference is used.

According to the sentence, the following case is OK.

fn main() {
    let mut s = String::from("hello");

    let r1 = &s; // no problem
    let r2 = &s; // no problem
    println!("{} and {}", r1, r2);
    // r1 and r2 are no longer used after this point

    let r3 = &mut s; // no problem
    println!("{}", r3);
}
Dangling Reference

If you have a reference to some data, the compiler will ensure that the data will not go out of scope before the reference to the data does.

String Slice Type

A string slice is a reference to part of a string, we can create slices using a range within brackets by specifying [stringing_index..ending_index].

posted @   kaleidopink  阅读(247)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示